Linux使用sudo权限执行部分命令不需要密码配置

来自三线的随记
Admin讨论 | 贡献2021年2月5日 (五) 15:59的版本

相关配置文件

/etc/sudoers


使用 #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

  1. As of Debian version 1.7.2p1-1, the default /etc/sudoers file created on
  1. installation of the package now includes the directive:
  1. #includedir /etc/sudoers.d
  1. This will cause sudo to read and parse any files in the /etc/sudoers.d
  1. directory that do not end in '~' or contain a '.' character.
  1. Note that there must be at least one file in the sudoers.d directory (this
  1. one will do), and all files in this directory should be mode 0440.
  1. Note also, that because sudoers contents can vary widely, no attempt is
  1. made to add this directive to existing sudoers files on upgrade.  Feel free
  1. to add the above directive to the end of your /etc/sudoers file to enable
  1. this functionality for existing installations if you wish!
  1. Finally, please note that using the visudo command is the recommended way
  1. to update sudoers content, since it protects against many failure modes.
  1. 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