一條 chmod -R 777 /* 少打一個點,瞬間摧毀系統權限體系。本文提供經實戰驗證的分級修復方案:優先搶救 SSH 登錄、繼續修復核心二進制特權位、最後通過乾淨機器導出 ACL 實現全盤權限還原,並提供開機自啟動保底腳本防止二次鎖死。
權限損壞後,新建 SSH 連接將因 sshd 配置文件權限錯誤、su/sudo 失效而無法建立。保持現有會話是唯一生路。
# 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 工具 (如未裝)
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
sudo。chmod -R、chown -R、rm -rf)先 echo 預覽,再執行。getfacl -R / > baseline.acl),納入備份策略。chattr +i 保護關鍵配置文件防誤改。