su 切换用户 及 sudo 详解
su 切换用户
命令 su
语法 su [-] username
后面可以跟”-“,也可以不跟。普通用户su不加username时就是切换到root用户,当然root用户同样可以su到普通用户。”-“这个字符的作用是,加上后会初始化当前用户的各种环境变量。加与不加的区别:
[test@localhost ~]$ pwd
/home/test
[test@localhost ~]$ su
密码:
[root@localhost test]# pwd
/home/test
[root@localhost test]# exit
exit
[test@localhost ~]$ su -
密码:
[root@localhost ~]# pwd
/root
如果不加”-“切换到root账户下时,当前目录没有变化。而加上”-“切换到root账户后,当前目录为root账户的家目录。这根直接登录root账户是一样的。
也可以在root登录时,直接以某个普通用户的身份去执行一条命令,用在脚本中比较合适。
[root@localhost ~]# su - test -c "touch /tmp/1.txt"
[root@localhost ~]# ls -l /tmp/1.txt
-rw-rw-r-- 1 test test 0 5月 14 03:45 /tmp/1.txt
可以看到/tmp/1.txt的所有者和属组都是 test
** 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的权利。这一行可以说时核心配置,该配置分为三部分,最左侧是用户名,指定哪个用户将拥有sudo的权利,第二部分左边的ALL其实是一个用户名,即,test用户可以切换到哪个用户的身份,如果时ALL就表示所有用户。小括号里面指定主机名或者主机IP,即,test用户从哪个IP登录来的,ALL就是所有。最后面那个ALL,用来指定test用户可以使用的命令都有哪些,ALL就是全部命令都可以。如果时多个命令,用英文逗号隔开。使用”visudo“命令编辑/etc/sudoers配置文件,其实它的操作方法和 vi 命令使用方法一样。
## Allow root to run any commands anywhere
root ALL=(ALL) ALL
test ALL=(ALL) ALL
验证权限:
[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 789 install.log test
456 anaconda-ks.cfg install.log.syslog test2
由于切换到test账户后的当前目录仍在/root下,test账户没有任何权限,所以 ls 的时候提示说权限不够。然而使用sudo ls 输入test账户自身的密码后就有权限了。初次使用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来获得帮助信息。下面介绍一个很实用的案例,我们的需求是把Linux服务器设置成这个样子:只允许使用普通账户登录,而普通账户登录后,可以不输入密码就能sudo切换到root账户下。具体配置:
[root@localhost ~]# visudo
然后在文件的最后加入三行:
User_Alias USER_SU = test,test1
Cmnd_Alias SU = /bin/su
USER_SU ALL=(ALL) NOPASSWD:SU
保存配置文件后,使用test,test1账户登录Linux。执行命令”sudo su-“切换到root账户,获取root账户所有的权限。
[root@localhost ~]# su - test
[test@localhost ~]$ sudo su -
[root@localhost ~]# whoami
root
不允许root直接登录除设置复杂密码外的方法:
不允许root远程登录linux
这个方法只适用于通过ssh远程登录linux的时候。修改配置文件/etc/sshd/sshd_config,在文件中查找”#PermitRootLogin yes“这句话,修改为”PermitRootLogin no“。它表示不允许root用户远程登录。保存配置文件后,需要重启sshd服务:
[root@localhost ~]# service sshd restart****
评论区