sudo 作为 www-data 用户运行特定命令的权限,无需密码

8 permissions php sudoers exec

我有一个网络服务器,也播放网络广播。作为 www-data 用户,我想运行一些命令,例如我在/etc/sudoers文件中做了这个:

www-data        ALL=(ALL) NOPASSWD: /usr/bin/amixer
Run Code Online (Sandbox Code Playgroud)

并形成 PHP 我可以在不使用密码的情况下通过以下方式操作音量:

exec('sudo -u user amixer set Master 3%-');
Run Code Online (Sandbox Code Playgroud)

和:

exec('sudo -u user amixer set Master 3%+');
Run Code Online (Sandbox Code Playgroud)

但是现在我希望能够通过运行命令来重新启动我自己的服务:

exec('sudo -u user service servicename restart');
Run Code Online (Sandbox Code Playgroud)

所以我试过:

www-data        ALL=(ALL) NOPASSWD: /usr/bin/amixer, NOPASSWD: /bin/service
Run Code Online (Sandbox Code Playgroud)

和这个:

www-data        ALL=(ALL) NOPASSWD: /usr/bin/amixer, /bin/service
Run Code Online (Sandbox Code Playgroud)

甚至这个:

www-data        ALL=(ALL) NOPASSWD: /usr/bin/amixer
www-data        ALL=(ALL) NOPASSWD: /bin/service
Run Code Online (Sandbox Code Playgroud)

但他们似乎都没有工作。请帮帮我。


对不起,伙计们 - 我的错误。我做了一些更改,尝试将表单 /sbin 链接到 /bin

现在我已将其更改为:

www-data        ALL=(ALL) NOPASSWD: /usr/bin/amixer, NOPASSWD: /usr/sbin/service
Run Code Online (Sandbox Code Playgroud)

它有效!谢谢!话题关闭。

Cal*_*imo 6

小心您的解决方案:您可以通过这种方式启动、停止或重新启动任何服务!

最好创建一个运行此命令的 shell 脚本:

echo "#!/bin/sh' > /usr/bin/amixer_restart
echo "sudo -u user service amixer restart' >> /usr/bin/amixer_restart
Run Code Online (Sandbox Code Playgroud)

授予足够的权限(550 表示 root 和组 www-data 可以读取和执行,没有人可以写入)

sudo chown root:www-data /usr/bin/amixer_restart
sudo chmod 550 /usr/bin/amixer_restart
Run Code Online (Sandbox Code Playgroud)

并允许 apache 在此脚本上执行 sudo:

www-data        ALL=(ALL) NOPASSWD: /usr/bin/amixer_restart
Run Code Online (Sandbox Code Playgroud)