允许用户在没有密码的情况下运行 systemctl/systemd 服务

Mik*_*iLL 48 sudo systemd

我希望默认用户ubuntu能够在不提示输入密码的情况下运行特定服务。

具体来说systemctl restart unicorn_my_app.service

已按照此处的说明将用户添加ubuntu到新创建的组LimitedAdmins,并通过以下方式确认:

$ getent group LimitedAdmins
LimitedAdmins:x:1001:ubuntu
Run Code Online (Sandbox Code Playgroud)

在包含以下文本的目录中创建了一个新文件limitedadmins(使用sudo vim/etc/sudoers.d

%LimitedAdmins ALL=NOPASSWD: /etc/init.d/unicorn_ofn_america restart, /etc/init.d/unicorn_ofn_america start

我也试过:

%LimitedAdmins ALL=NOPASSWD: /bin/systemctl/unicorn_ofn_america restart, /bin/systemctl/unicorn_ofn_america start

(和/bin/systemd

的内容/etc/sudoers/是用sudo visudo(或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.
#
# See the man page for details on how to write a sudoers file.
#
Defaults    env_reset
Defaults    mail_badpass
Defaults    secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"

# Host alias specification

# User alias specification

# Cmnd alias specification

# User privilege specification
root    ALL=(ALL:ALL) ALL

# Members of the admin group may gain root privileges
%admin ALL=(ALL) ALL

# Allow members of group sudo to execute any command
%sudo   ALL=(ALL:ALL) ALL

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

#includedir /etc/sudoers.d
Run Code Online (Sandbox Code Playgroud)

(哈希符号#includedir不是注释,而是#include 指令语法的一部分)。

但是运行后还是有密码提示 systemctl restart unicorn_my_app.service

init.d目录中有服务:

$ ls -l /etc/init.d | grep unicorn
-rwxr--r-- 1 ubuntu ubuntu 1874 Oct 29 06:47 unicorn_my_app
Run Code Online (Sandbox Code Playgroud)

755在应用程序上尝试了 chmodding ,但不要认为这应该有所作为,因为ubuntu无论如何都拥有它。

甚至尝试重新启动系统没有任何区别。我是否缺少一个步骤,例如重新启动/重新加载)?配置有问题?

我还应该提到,我曾经vim在 中创建新文件/etc/sudoers.d,因为该visudo命令似乎用于编辑/etc/sudoers.

更新

看起来您可以使用visudo. 见下文

ros*_*uav 65

sudoers 文件相当灵活,随之而来的是复杂性。您在这里想要的是允许/bin/systemctl使用特定参数访问 command :

%LimitedAdmins ALL=NOPASSWD: /bin/systemctl restart unicorn_my_app.service

基本上,您只需使用您将键入的确切命令行,为安全起见对路径名进行硬编码,然后将其放入您的 sudoers 文件(或/etc/sudoers.d)。请注意,就 sudo 而言,'start' 和 'restart' 是完全不同的;允许一个不会授予另一个访问权限。

  • 您将运行`sudo /bin/systemctl restart unicorn_my_app.service`,然后它应该在没有密码的情况下运行。(作为评论发布,以防 PsiOps 的答案与此答案分开) (10认同)
  • 注意:在其他发行版中,`systemctl` 位于 `/usr/bin` 中 :-(。 (5认同)

小智 7

我也认为 visudo 只能起作用,/etc/sudoers但幸运的是,我错了。

visudo可用于修改现有文件/etc/sudoers.d或创建新文件。-f 参数允许这样做。如果像这样调用命令:

visudo -f /etc/sudoers.d/permissions_for_subset_of_users

您可以使用 visudo 的验证功能来安全编辑 sudoers。

此外,如果您正在使用某种 CI/CD 或配置管理,则可以用于visudo -cf <name_of_file>运行配置验证。(我们的首席系统管理员提供了第二条知识)。

参考: https: //www.sudo.ws/man/1.8.13/visudo.man.html