3.7 su命令
3.8 sudo命令
3.9 限制root远程登录
一、su命令
su命令:用于切换用户
用法: su 选项 username
示例1:完全切换用户,包括家目录、权限、环境变量。加上"-"就是完全切换的意思,一般su时最好加上"-"
[root@wxy01 ~]# su - wxy
[wxy@wxy01 ~]$
示例2:切换用户并执行某个命令后退回至原用户。
[root@wxy01 ~]# su - -c "touch /tmp/sutest.txt" wxy
[root@wxy01 ~]# ll /tmp/sutest.txt
-rw-r--r-- 1 wxy test 0 Sep 21 17:11 /tmp/sutest.txt
[root@wxy01 ~]#
以上就是在root用户下,切换到wxy用户然后创建了一个sutest.txt文件并退回到了root用户。我们查看这个文件所属组确实是"wxy"
如果一个用户没有家目录和配置文件则会出现以下问题:
[root@wxy01 ~]# su - test5
su: warning: cannot change directory to /home/111: No such file or directory
-bash-4.2$ ll
ls: cannot open directory .: Permission denied
想要解决这个问题创建一个家目录然后拷贝配置文件:
[root@wxy01 ~]# mkdir /home/111
[root@wxy01 ~]# cp /etc/skel/.bash* /home/111/
[root@wxy01 ~]# su - wxy5
su: user wxy5 does not exist
[root@wxy01 ~]# su - test5
Last login: Fri Sep 21 17:16:25 CST 2018 on pts/0
[test5@wxy01 ~]$ ll
total 0
[test5@wxy01 ~]$
二、sudo命令
sudo命令:让普通用户临时拥有root才可以执行的命令。
root能够sudo是因为sudoers配置文件文件中有一行 “root ALL=(ALL) ALL”,如果想让一个普通用户拥有sudo的权限,在该行下面加入 “wxy ALL=(ALL) ALL” 即可。
使用visduo命令编辑sudoers配置文件,加入一行wxy ALL=(ALL) ALL,保存退出。
[wxy@wxy01 ~]$ ls /root/
ls: cannot open directory /root/: Permission denied
[wxy@wxy01 ~]$ sudo ls /root/
[sudo] password for wxy:
kibana-6.4.1-x86_64.rpm test zabbix-release-3.2-1.el7.noarch.rpm.1
tcping-1.3.5 wget-log
tcping-1.3.5.tar.gz zabbix-release-3.2-1.el7.noarch.rpm
[wxy@wxy01 ~]$
以上看到给wxy用户加入sudo权限后,就可以使用ls /root 命令查看root目录下的文件了。
ps:首次使用sudo命令需要输入用户密码,下次再使用就不用再输入密码了。
一个个用户添加sudo权限太麻烦,也可以按用户组进行添加:在配置文件中把“# %wheel ALL=(ALL) ALL” 前面的 ‘# ‘ 去掉后,wheel这个组的所有用户都拥有了sudo的权利。接下来就需要你把想让有sudo权利的所有用户加入到wheel这个组中即可。
三、限制root远程登录
为了安全如果不想root用户远程登录,可以使用以下配置限制root远程登录:
修改配置文件/etc/ssh/sshd_config,把#PermitRootLogin yes修改为PermitRootLogin no,保存配置文件后,重启sshd服务,如下:
#systemctl restart sshd.service
这种方法只适用于通过ssh远程登录Linux的情况。