将本地内容添加到 /etc/sudoers.d/ 而不是通过 visudo 直接修改 sudoers 文件。

请问你能给我一些关于/etc/sudoers.d/的示例和更详细的说明吗?
我想给一些组赋予sudo执行某些命令的权限,但要以适当的方式进行,不要在多用户机器上创建不必要的漏洞,破坏Ubuntu安全模型。
在古代,我做过一些简单的sudoers自定义,但显然现在/etc/sudoers.d/是更合适的方式,我想更好地了解它。
1个回答

正如这个问题所说,/etc/sudoers是一个系统范围的配置文件,可能会在系统升级时自动更改,并且对不正确的更改非常脆弱。您可能会失去访问权限或使系统无法启动。
$ sudo cat /etc/sudoers
#
# This file MUST be edited with the 'visudo' command as root.
#
# Please consider adding local content in /etc/sudoers.d/ instead of
# directly modifying this file.
#

(... some other content ...)

# See sudoers(5) for more information on "#include" directives:

#includedir /etc/sudoers.d

与您可能期望的相反,#includedir指令并非注释。它的作用是使sudo还会读取和解析/etc/sudoers.d目录中的任何文件(不以'~'结尾或包含'.'字符的文件除外)。
$ ls -l /etc/sud*
-r--r----- 1 root root  755 sty 20 17:03 /etc/sudoers

/etc/sudoers.d:
total 7
-r--r----- 1 root root 958 mar 30  2016 README
$ sudo cat /etc/sudoers.d/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.
#

/etc/sudoers不同,/etc/sudoers.d的内容在系统升级后仍然存在,因此最好在那里创建文件而不是修改/etc/sudoers
您可能希望使用visudo命令编辑此目录中的文件。
$ sudo visudo -f /etc/sudoers.d/veracrypt
  GNU nano 2.5.3        File: /etc/sudoers.d/veracrypt.tmp                      

# Users in the veracryptusers group are allowed to run veracrypt as root.
%veracryptusers ALL=(root) NOPASSWD:/usr/bin/veracrypt

请注意,visudo 可能会使用不同的编辑器,而不是在 https://help.ubuntu.com/community/Sudoers 中描述的 nano
以下是我找到的一些有用的链接:

7/etc/sudoers.d文件中的错误并不会导致sudo崩溃,这是不正确的。这些文件会被连接到/etc/sudoers文件中,同样的规则也适用于这些文件。 - tobltobs
2没错,你确实可以通过不正确的文件来破坏系统,但这种可能性较小。#includedir并不仅仅是简单的拼接 - 在包含时会进行一些检查,以便检测到最明显的错误,并且你可以轻松恢复。然而要小心 - 你总是可以用锋利的刀子伤到自己,所以要小心处理它;-) - Pawel Debski
4@RichardRiley 请参考https://unix.stackexchange.com/questions/244064/why-are-the-include-and-includedir-directives-in-sudo-prefixed-with-the-pound - Xunnamius