Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Linux 系統文件權限誤操作緊急修復指南:從 SSH 恢復到全盤 ACL 還原

編輯:Linux 教學

一條 chmod -R 777 /* 少打一個點,瞬間摧毀系統權限體系。本文提供經實戰驗證的分級修復方案:優先搶救 SSH 登錄、繼續修復核心二進制特權位、最後通過乾淨機器導出 ACL 實現全盤權限還原,並提供開機自啟動保底腳本防止二次鎖死。

核心原則:絕不關閉當前 Root 終端!

權限損壞後,新建 SSH 連接將因 sshd 配置文件權限錯誤、su/sudo 失效而無法建立。保持現有會話是唯一生路。

第一階段:搶救 SSH 與 Root 切換能力

# 1. 修復 /etc 關鍵文件權限
cd /etc
chmod 644 passwd group shadow
chmod 400 gshadow

# 2. 修復 SSH 配置與宿主金鑰權限
cd /etc/ssh
chmod 600 moduli ssh_host_*_key
chmod 644 ssh_config ssh_host_*_key.pub
chmod 640 sshd_config

# 3. 修復 su/sudo 特權位 (關鍵!)
chmod u+s $(which su)
chmod u+s $(which sudo)
chmod 4755 /usr/bin/sudo   # 確保 sudo 正確
chmod 4755 /usr/bin/su     # 確保 su 正確

# 4. 重啟 sshd 驗證
systemctl restart sshd
# 或 service sshd restart

此時應能新建 SSH 連接並 su - root 成功。若 systemctl 不可用,嘗試 /etc/init.d/sshd restart。

第二階段:全盤權限還原(ACL 方案)

手動逐個修復不可行,需借助同版本、同架構、最小安裝的乾淨參考機。

在參考機導出完整 ACL

# 安裝 acl 工具 (如未裝)
yum install -y acl   # 或 apt-get install acl

# 導出根目錄完整 ACL (排除虛擬文件系統)
getfacl -R / --skip-base -e proc -e sys -e dev -e run -e tmp -e var/lib/docker -e var/lib/kubelet > /root/linux.permissions.acl

# 壓縮傳輸
gzip /root/linux.permissions.acl
scp /root/linux.permissions.acl.gz root@target-server:/root/

在目標機還原

gunzip /root/linux.permissions.acl.gz
# 預演 (不實際修改)
setfacl --test --restore=/root/linux.permissions.acl

# 正式還原
setfacl --restore=/root/linux.permissions.acl

注意:setfacl --restore 會覆蓋現有 ACL,若目標機安裝了額外軟件(如 Docker、K8s、自編譯程序),其權限會被重置為參考機狀態(可能不存在)。建議先備份關鍵業務目錄權限:

getfacl -R /opt /usr/local /data /var/lib/mysql > /root/business.permissions.acl

第三階段:開機自啟動保底腳本(防二次鎖死)

在還原前創建,確保若重啟後 SSH 掛掉仍能自動修復:

cat > /root/emergency_ssh_fix.sh <<'EOF'
#!/bin/bash
cd /etc
chmod 644 passwd group shadow
chmod 400 gshadow
cd /etc/ssh
chmod 600 moduli ssh_host_*_key
chmod 644 ssh_config ssh_host_*_key.pub
chmod 640 sshd_config
chmod u+s $(which su)
chmod u+s $(which sudo)
systemctl restart sshd 2>/dev/null || service sshd restart 2>/dev/null
EOF
chmod +x /root/emergency_ssh_fix.sh

# 加入 rc.local (需確保 rc.local 可執行且啟用)
echo "/root/emergency_ssh_fix.sh &" >> /etc/rc.local
chmod +x /etc/rc.d/rc.local
systemctl enable rc-local 2>/dev/null

重啟驗證與收尾

reboot
# 重啟後檢查
ssh user@server
# 正常登錄並 su - root 成功後,移除保底腳本
sed -i '/emergency_ssh_fix.sh/d' /etc/rc.local

業務數據權限補充

ACL 還原僅覆蓋系統文件。業務目錄(/data、/opt/app、/var/www)需結合備份的 business.permissions.acl 或根據應用文檔手動修復:

# 典型 Web 目錄權限
chown -R www-data:www-data /var/www
find /var/www -type d -exec chmod 755 {} \;
find /var/www -type f -exec chmod 644 {} \;
chmod 750 /var/www/wp-config.php  # 敏感配置

# 數據庫目錄
chown -R mysql:mysql /var/lib/mysql
chmod 750 /var/lib/mysql

教訓總結

  • 生產環境禁用 Root 直接登錄,使用普通用戶 + sudo。
  • 危險操作(chmod -R、chown -R、rm -rf)先 echo 預覽,再執行。
  • 建立權限基線備份(getfacl -R / > baseline.acl),納入備份策略。
  • 考慮使用 chattr +i 保護關鍵配置文件防誤改。
Copyright © Windows教程網 All Rights Reserved