注意
一个用户能否使用 sudo 命令,取决于 /etc/sudoers 文件的设置。/etc/sudoers 是一个文本文件,因其有特定的语法,不能直接用 vim 或者 vi 来编辑它,需要用 visudo 这个命令。
[root@localhost ~]# visudo
······
## Allow root to run any commands anywhere
root ALL=(ALL) ALL
## Allows members of the 'sys' group to run networking, software,
## service management apps and more.
# %sys ALL = NETWORKING, SOFTWARE, SERVICES, STORAGE, DELEGATING, PROCESSES, LOCATE, DRIVERS
## Allows people in group wheel to run all commands
%wheel ALL=(ALL) ALL
## Same thing without a password
# %wheel ALL=(ALL) NOPASSWD: ALL
## Allows members of the users group to mount and unmount the
## cdrom as root
# %users ALL=/sbin/mount /mnt/cdrom, /sbin/umount /mnt/cdrom
## Allows members of the users group to shutdown this system
# %users localhost=/sbin/shutdown -h now
## Read drop-in files from /etc/sudoers.d (the # here does not mean a comment)
#includedir /etc/sudoers.d
·····
1. 第一个表示用户名,如 root 、ubuntu 等;
2. 接下来等号左边的 ALL 表示允许从任何主机登录当前的用户账户;
3. 等号右边的 ALL 表示:这一行行首对一个的用户可以切换到系统中任何一个其它用户;
4. 行尾的 ALL 表示:当前行首的用户,能以 root 用户的身份下达什么命令,ALL 表示可以下达任何命令。
# test2执行查询shadow文件,提示权限不够
[test2@localhost ~]$ tail -f /etc/shadow
tail: cannot open ‘/etc/shadow’ for reading: Permission denied
# root下修改sudoer文件
[root@localhost ~]# visudo
#includedir /etc/sudoers.d
test2 ALL=(ALL) NOPASSWD: ALL
# 切换test2用户,sudo执行之前的命令
[test2@localhost ~]$ sudo tail -f /etc/shadow
setroubleshoot:!!:18715::::::
gdm:!!:18715::::::
rpcuser:!!:18715::::::
nfsnobody:!!:18715::::::
安全
如果一个用户在 /etc/sudoers 文件中,那么它就具有 sudo 权限,就能通过 sudo su - 或者 sudo -i 等命令切换到 root 用户了,那这时这个用户就变成 root 用户了,会对系统造成很大的威胁。所以如果在编辑 /etc/sudoers 文件赋予某种用户 sudo 权限时,必须要确定该用户是可信任的,不会对系统造成恶意破坏,否则将所有 root 权限都赋予该用户将会有非常大的危险。
当然,root 用户也可以编辑 /etc/sudoers 使用户只具备一部分权限,即只能执行一小部分命令。