我有一个 sudoers 文件,允许用户在没有密码的情况下运行 sudo 命令(主要是为了管理特定服务)。我想大大减少整个配置的重复:
这是一个简单的版本:
Cmd_Alias NGINX = \
/bin/systemctl start nginx, \
/bin/systemctl stop nginx, \
/bin/systemctl restart nginx, \
/bin/systemctl reload nginx, \
/bin/systemctl status nginx
# glob php version, to save this breaking on version changes
Cmd_Alias PHP = \
/bin/systemctl start php[0-9].[0-9]-fpm, \
/bin/systemctl stop php[0-9].[0-9]-fpm, \
/bin/systemctl restart php[0-9].[0-9]-fpm, \
/bin/systemctl reload php[0-9].[0-9]-fpm, \
/bin/systemctl status php[0-9].[0-9]-fpm
...
username ALL = NOPASSWD: NGINX
username ALL = NOPASSWD: PHP
...
真实版本有几个指定的服务,它们都遵循相同的格式。因此,理想情况下,更好的做法是:
Cmd_Alias SERVICES = \
/bin/systemctl {start,stop,restart,reload,status} {nginx,php[0-9].[0-9]-fpm,foo,bar,alice,bob}
username ALL = NOPASSWD: SERVICES
但似乎不允许大括号扩展。我收到有关逗号的语法错误,无论它们是否被转义。
所以我检查了一下man sudoers
,它提到了通配符/通配符的基本形式是可能的(这对于 PHP 版本的通配符非常有效,如上所述):
Wildcards
sudo allows shell-style wildcards (aka meta or glob characters) to be used in host names, path names, and command line arguments in
the sudoers file. Wildcard matching is done via the glob(3) and fnmatch(3) functions as specified by IEEE Std 1003.1 (“POSIX.1”).
* Matches any set of zero or more characters (including white space).
? Matches any single character (including white space).
[...] Matches any character in the specified range.
[!...] Matches any character not in the specified range.
\x For any character ‘x’, evaluates to ‘x’. This is used to escape special characters such as: ‘*’, ‘?’, ‘[’, and ‘]’.
但是否可以使用其他方法来减少重复呢?也许是变量?我不知道的别名方法?
最好是期望的用户输入仍然获得期望的结果,即sudo systemctl status whatever
而不是用脚本解析用户输入。