# 通过visudo命令来编辑/etc/sudoers,添加和修改用户的sudo权限 # 如下表示允许usera切换到root权限执行/sbin/nginx相关命令 $ visudo ... usera ALL=(root) /sbin/nginx # 切换的usera用户,默认usera用户没有权限执行nginx命令 $ su - usera $ nginx -t nginx: [alert] could not open error log file: open() "/var/log/nginx/error.log" failed (13: Permission denied) 2021/03/16 20:55:34 [warn] 13088#0: the "user" directive makes sense only if the master process runs with super-user privileges, ignored in /etc/nginx/nginx.conf:5 nginx: the configuration file /etc/nginx/nginx.conf syntax is ok 2021/03/16 20:55:34 [emerg] 13088#0: open() "/run/nginx.pid" failed (13: Permission denied) nginx: configuration file /etc/nginx/nginx.conf test failed # 添加sudo即可执行,注意需要输入usera用户的密码 $ sudo nginx -t [sudo] password for usera: nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful
# 如下表示userb用户可以切换到root执行任何命令,且无需输入密码,即授权userb为管理员 $ visudo ... userb ALL=(ALL) NOPASSWD: ALL # 切换到userb用户 $ su - userb $ sudo nginx -t nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful # 可以切换到root用户执行任何命令,且无需加sudo $ sudo su - root $ whoami root $ touch /root/userb $ ll /root/userb -rw-r--r-- 1 root root 0 Mar 16 21:01 /root/userb
# 查看usera和userb的sudo权限 $ sudo -l -U usera Matching Defaults entries for usera on centos7: !visiblepw, always_set_home, match_group_by_gid, always_query_group_plugin, env_reset, env_keep="COLORS DISPLAY HOSTNAME HISTSIZE KDEDIR LS_COLORS", env_keep+="MAIL PS1 PS2 QTDIR USERNAME LANG LC_ADDRESS LC_CTYPE", env_keep+="LC_COLLATE LC_IDENTIFICATION LC_MEASUREMENT LC_MESSAGES", env_keep+="LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER LC_TELEPHONE", env_keep+="LC_TIME LC_ALL LANGUAGE LINGUAS _XKB_CHARSET XAUTHORITY", secure_path=/sbin\:/bin\:/usr/sbin\:/usr/bin User usera may run the following commands on centos7: (root) /sbin/nginx $ sudo -l -U userb ... User userb may run the following commands on centos7: (ALL) NOPASSWD: ALL