一、su命令
- su命令用於切換當前用戶身份到其他用戶身份,變更時須輸入所要變更的用戶帳號與密碼。
- 語法:su(選項)(參數)
- -c<指令>或--command=<指令>:執行完指定的指令後,即恢復原來的身份;
-f或——fast:適用於csh與tsch,使shell不用去讀取啓動文件;
-l或——login:改變身份時,也同時變更工作目錄,以及HOME,SHELL,USER,logname。此外,也會變更PATH變量;
-m,-p或--preserve-environment:變更身份時,不要變更環境變量;
-s或--shell=:指定要執行的shell;
--help:顯示幫助;
--version;顯示版本信息。 - 命令:
su -c ls root
變更帳號爲root並傳入-f選項給新執行的shell:
su root -f
變更帳號爲test並改變工作目錄至test的家目錄:
su -test
二、sudo命令
- 用su是可以切換用戶身份,如果每個普通用戶都能切換到root身份,如果某個用戶不小心泄漏了root的密碼,那豈不是系統非常的不安全?沒有錯,爲了改進這個問題,產生了sudo這個命令。使用sudo執行一個root才能執行的命令是可以辦到的,但是需要輸入密碼,這個密碼並不是root的密碼而是用戶自己的密碼。默認只有root用戶能使用sudo命令,普通用戶想要使用sudo,是需要root預先設定的,即,使用 visudo 命令去編輯相關的配置文件/etc/sudoers. 如果沒有visudo這個命令,請使用 yum install -y sudo 安裝。
- 默認root能夠sudo是因爲這個文件中有一行 “root ALL=(ALL) ALL” 在該行下面加入 “test ALL=(ALL) ALL” 就可以讓test用戶擁有了sudo的權利。使用 “visudo” 命令編輯/etc/sudoers配置文件,它的操作方法和 “vi” 命令使用方法是一樣的,按 ‘i’ 進入編輯模式,編輯完成後,按 “Esc” ,再輸入 ”:wq” 完成保存。
## Allow root to run any commands anywhere
root ALL=(ALL) ALL
test ALL=(ALL) ALL
此時可以驗證一下test賬戶的權限了。
[root@localhost ~]# su test
[test@localhost root]$ ls
ls: 無法打開目錄.: 權限不夠
[test@localhost root]$ sudo ls
We trust you have received the usual lecture from the local System
Administrator. It usually boils down to these three things:
#1) Respect the privacy of others.
#2) Think before you type.
#3) With great power comes great responsibility.
[sudo] password for test:
123 456 789 anaconda-ks.cfg dirb install.log install.log.syslog test test1 test2 test3
由於切換到test賬戶後的當前目錄依舊是在/root 下,test賬戶沒有任何權限,所以 ‘ls’ 的時候提示說權限不夠,然而使用 sudo ls 輸入test賬戶自身的密碼後就有權限了。初次使用sudo 時會有上面的一大段提示,而後再次使用sudo 命令則不再提示。
如果每增加一用戶就設置一行,這樣太麻>煩了。所以你可以這樣設置。把 “# %wheel ALL=(ALL) ALL” 前面的 ‘# ‘ 去掉,讓這一行生效。它的意思是,wheel這個組的所有用戶都擁有了sudo的權利。接下來就需要你把想讓有sudo權利的所有用戶加入到wheel這個組中即可。
## Allows people in group wheel to run all commands
%wheel ALL=(ALL) ALL
配置文件/etc/sudoers包含了諸多配置項,可以使用命令 man sudoers 來獲得幫助信息。
只允許使用普通賬戶登陸,而普通賬戶登錄後,可以不輸入密碼就能sudo切換到root賬戶。如下配置:
[root@localhost ~]# visudo
然後在文件的最後面加入三行:
User_Alias USER_SU = test, test1, gaohanwei
Cmnd_Alias SU = /bin/su
USER_SU ALL=(ALL) NOPASSWD: SU
保存配置文件後,使用test, test1, gaohanwei 三個賬戶登陸Linux後,執行命令 sudo su - 切換到root賬戶,獲取root賬戶的所有權利。
[root@localhost ~]# su - test
[test@localhost ~]$ sudo su -
[root@localhost ~]# whoami
root
如果不想讓root很簡單的直接登錄,我們就可以使用keypass工具來保存記錄一個很複雜的密碼。
三、限制root遠程登錄
/etc/ssh/sshd_config爲sshd服務的配置文件,默認允許root賬戶通過ssh遠程登錄linux。要想不允許root用戶遠程登錄linux,具體操作方法如下:
修改配置文件/etc/ssh/sshd_config,在文件中查找#PermitRootLoginyes並修改爲PermitRootLogin no。保存配置文件後,需要重啓sshd服務,如下:
#systemctl restart sshd.service
這種方法只適用於通過ssh遠程登錄Linux的情況。