Centos8中恢復根目錄為默認權限
本文中介紹如何從意外運行# chmod -R 777 /命令,在Centos8操作系統上恢復默認權限。
本文中我們將故意在一個測試服務器上運行chmod 777命令,并嘗試通過運行兩個命令進行恢復。就是如下兩條命令:
- # rpm --setugids -a
- # rpm --setperms -a
當再測試機上面執行下面命令之后,所有文件權限都會變成777。
- [root@localhost ~]# chmod -R 777 /
列出根目錄下面的內容:
- [root@localhost ~]# ls -al /
下面是SSH相關的重要文件,需要有正確的權限和所有權。但是,由于運行chmod 777,以下所有文件都具有錯誤的權限。
- [root@localhost ~]# ll /etc/ssh/
- total 588
- -rwxrwxrwx. 1 root root 563386 May 11 2019 moduli
- -rwxrwxrwx. 1 root root 1727 May 11 2019 ssh_config
- drwxrwxrwx. 2 root root 28 Dec 29 2019 ssh_config.d
- -rwxrwxrwx. 1 root root 4444 May 11 2019 sshd_config
- -rwxrwxrwx. 1 root ssh_keys 480 Dec 29 2019 ssh_host_ecdsa_key
- -rwxrwxrwx. 1 root root 162 Dec 29 2019 ssh_host_ecdsa_key.pub
- -rwxrwxrwx. 1 root ssh_keys 387 Dec 29 2019 ssh_host_ed25519_key
- -rwxrwxrwx. 1 root root 82 Dec 29 2019 ssh_host_ed25519_key.pub
- -rwxrwxrwx. 1 root ssh_keys 1799 Dec 29 2019 ssh_host_rsa_key
- -rwxrwxrwx. 1 root root 382 Dec 29 2019 ssh_host_rsa_key.pub
帶有chmod 777權限的SSH
下面嘗試通過SSH遠程登錄服務器。由于主機密鑰文件權限都變成了777了,所以登錄會被拒絕。
下面再終端中ssh登錄本機出現下面問題:
下面使用Xshell登錄服務器,同樣不能登錄成功:
- [C:\~]$ ssh root@192.168.43.131
- Connecting to 192.168.43.131:22...
- Connection established.
- To escape to local shell, press 'Ctrl+Alt+]'.
- Connection closing...Socket close.
- Connection closed by foreign host.
- Disconnected from remote host(192.168.43.131:22) at 10:28:06.
- Type `help' to learn how to use Xshell prompt.
恢復權限
需要恢復權限,我們需要加載Centos8的系統鏡像,開機啟動光盤鏡像:
在VMware Workstation中,加載光盤,并開機器用。開機按F2,進入BIOS,切換到Boot選項卡。將CD-ROM Drive移動到Hard Drive上面。按F10保存并重啟。
選擇Troubleshooting,然后選擇進入救援模式。
當進入下面界面時,選擇1,直接進入shell界面。
使用chroot命令將/mnt/sysroot切換為根目錄:
- sh-4.4# chroot /mnt/sysroot
使用以下兩個命令運行,以恢復所有文件,目錄和配置的權限。運行此命令時,它將引發權限被拒絕錯誤,并且無法訪問錯誤。只是忽略錯誤。
- # rpm --setugids -a
- # rpm --setperms -a
參數說明:
--setugids - 設置RPM包文件的用戶/組所有權。
--setperms - 設置RPM包文件的權限。
-a - 適用于所有已安裝的RPM軟件包。
完成操作之后,退出,并重啟:
- # exit
- # reboot
查看權限、SSH連接服務器測試
下面登錄系統之后,看一下根目錄的權限是否恢復正常:
- # ls -l /
運行ssh登錄,發現不能登錄。使用netstat -tlunp發現ssh端口沒有監聽中,使用systemctl status sshd發現服務沒有啟動,啟動sshd服務時發現不能啟動,下面查找原因:
發現密鑰文件的權限還是777,沒有還原:
下面設置密鑰文件權限:
- # chmod 644 /etc/ssh/ssh_config
- # chmod 600 /etc/ssh/sshd_config
- # chmod 640 /etc/ssh/ssh_host_rsa_key /etc/ssh/ssh_host_ecdsa_key /etc/ssh/ssh_host_ed25519_key
- # chmod 644 /etc/ssh/ssh_host_rsa_key.pub /etc/ssh/ssh_host_ecdsa_key.pub /etc/ssh/ssh_host_ed25519_key.pub
下面再次啟動sshd試一下:
- # systemctl enable sshd --now
- # netstat -tlunp
可以看到啟動成功了。ssh遠程登錄試一下,看到登錄成功了。
總 結
就這樣,我們已經成功還原了已安裝的RPM軟件包的權限并恢復了服務器。切勿在任何文件系統或配置上使用chmod 777。
本文轉載自微信公眾號「Linux就該這么學」,可以通過以下二維碼關注。轉載本文請聯系Linux就該這么學公眾號。