Linux使用sudo权限执行部分命令不需要密码配置
来自三线的随记
相关配置文件
/etc/sudoers
/etc/sudoers.d
使用 #include
和 #includedir
插入别的配置文件
## Read drop-in files from /private/etc/sudoers.d ## (the '#' here does not indicate a comment) #includedir /private/etc/sudoers.d
Including other files from within sudoers It is possible to include other sudoers files from within the sudoers file currently being parsed using the #include and #includedir directives. This can be used, for example, to keep a site-wide sudoers file in addition to a local, per-machine file. For the sake of this example the site-wide sudoers file will be /etc/sudoers and the per-machine one will be /etc/sudoers.local. To include /etc/sudoers.local from within /etc/sudoers we would use the following line in /etc/sudoers: #include /etc/sudoers.local
- ⚠️注意, 此处的
#includedir
中的#
并不是代表注释该行 - 如果用的是 #includedir 指令,目标目录下面的规则文件,不要有文件拓展名(.xxx),否则很有可能不生效,原因如下
root@ubuntu:/etc/sudoers.d# cat README # # As of Debian version 1.7.2p1-1, the default /etc/sudoers file created on # installation of the package now includes the directive: # # #includedir /etc/sudoers.d # # This will cause sudo to read and parse any files in the /etc/sudoers.d # directory that do not end in '~' or contain a '.' character. # # Note that there must be at least one file in the sudoers.d directory (this # one will do), and all files in this directory should be mode 0440. # # Note also, that because sudoers contents can vary widely, no attempt is # made to add this directive to existing sudoers files on upgrade. Feel free # to add the above directive to the end of your /etc/sudoers file to enable # this functionality for existing installations if you wish! # # Finally, please note that using the visudo command is the recommended way # to update sudoers content, since it protects against many failure modes. # See the man page for visudo for more information. #
配置用户拥有sudo权限
root ALL = (ALL) ALL %group-id ALL = (ALL) ALL
配置sudo所有命令不需要密码认证
your-user-name ALL = (ALL) NOPASSWD:ALL
- ⚠️注意,配置参数能被下文覆盖,所以如果前文中配置了NOPASSWD:ALL,但是假设后文又重新配置了
(ALL) ALL
,则会在执行sudo的时候还是需要密码
配置sudo对于特定命令不需要密码认证
user-id ALL = (ALL) NOPASSWD:/usr/sbin/tcpdump user-id ALL = (ALL) NOPASSWD:/sbin/route user-id ALL = (ALL) NOPASSWD:/usr/local/bin/openconnect