如何以普通用户身份运行reboot而无需输入密码?

Lev*_*der 3 debian sudo

我的目标是在不输入密码的情况下使用 reboot 作为我的用户名。我怎样才能做到这一点?

我已经阅读了允许用户在没有密码的情况下使用 sudo并遵循了建议,但它仍然对我不起作用。这是我的,/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
myusername  ALL=NOPASSWD:/sbin/reboot

# 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)

然后我跑

sudo reboot
Run Code Online (Sandbox Code Playgroud)

并被要求输入密码。如何在reboot不被要求输入密码的情况下以普通用户身份运行?

这是sudo -l输出:

Matching Defaults entries for myusername on this host:
    env_reset, mail_badpass,
    secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin

User myusername may run the following commands on this host:
    (root) NOPASSWD: /sbin/reboot
    (ALL : ALL) ALL
Run Code Online (Sandbox Code Playgroud)

我也试过

myusername  ALL=NOPASSWD:/bin/ls
Run Code Online (Sandbox Code Playgroud)

sudo ls仍然要求输入密码,所以这似乎是一个普遍问题,而不是特定于reboot.

ter*_*don 6

首先,不要,我再说一遍,不要试图让你的用户在任何时候都拥有 root 权限,这是所有安全风险的根源,不仅没有必要,而且是在自找麻烦。

无论如何,如果您希望您的用户能够运行特定命令,则需要将此行添加到sudoersterdon当然要更改为您的用户名):

terdon ALL=NOPASSWD:/sbin/reboot
Run Code Online (Sandbox Code Playgroud)

然后您可以在sudo reboot 不输入密码的情况下运行它。但是,您将始终需要运行它sudo,最好的方法是sudo对某些命令无密码。

这是因为系统的工作方式。例如shutdown -r,当您尝试以普通用户身份运行时,您会收到以下消息:

$ shutdown -r
shutdown: you must be root to do that!
Run Code Online (Sandbox Code Playgroud)

这与 无关,有sudo问题的命令只是检查您的用户 ID 是否为 1(超级用户),如果不是,则不会让您运行它。您可以将您的系统设置为让另一个用户作为用户 ID 1,但这只会更改用户名,root并且会无缘无故地带来很多麻烦(并且无论如何都不会帮助您执行您正在尝试的操作)。

因此,除非您实际以 userid 为 1 的用户身份登录,否则您将始终必须使用sudo来运行特权命令。唯一的解决方法是reboot在 shell 的配置文件(~/.bashrc例如)中创建别名(或函数或脚本):

alias reboot='sudo shutdown -r now'
Run Code Online (Sandbox Code Playgroud)

这样,由于您已经在 中设置shutdown为无密码/etc/sudoers,您将能够运行

$ reboot
Run Code Online (Sandbox Code Playgroud)

并得到你想要的结果。