如何从 PHP 中调用需要 SUDO 权限的 shell 脚本?

46

我有一个需要使用SUDO才能正常工作的bash脚本文件。

我可以在命令行中使用SUDO运行它,但是我需要输入SUDO密码。

我想通过shell_exec从php中运行该脚本,但如果我调用SUDO,它不像命令行那样会提示我输入密码。有没有一种方法可以在sudo调用时传递密码?

我该怎么做?


顺便说一下,我正在自己的Ubuntu 10.04机器上运行这个,使用的是Apache2和PHP5。 - JD Isaacks
你应该考虑更改脚本的权限。例如,你可以将组更改为apache用户(www-data),并授予组执行权限:chgrp www-data script.sh && chmod g+x script.sh - Danilo Bargen
1
@John Isaacks:啊。看一下setuid位:http://en.wikipedia.org/wiki/Setuid - Danilo Bargen
1
为什么svn commit需要root权限? - Stephen
2
@John Isaacks:这几乎肯定是您的svn配置问题。您不想开始分发根访问权限以解决它,否则您最终会得到一个非常不安全的系统。花些时间在svn文档中,为自己和可能的“www-admin”访问svn存储库的部分提供访问权限。(我可以告诉您,但我已经好几年没碰过svn了) - Stephen
显示剩余2条评论
4个回答

48

使用visudo编辑sudoers文件,并添加一个规则,允许Web服务器用户在没有密码的情况下运行该命令。例如:

www-data ALL=NOPASSWD: /path/to/script

只要 Web 服务器以“www-data”用户身份运行,它就适用于任何 Web 服务器。 - Maxime Launois

8
这个问题有多种解决方案。
  • First of all, consider changing the script permissions, if reason why you want sudo is simply a permission issue (see the comment I added to the question above).

  • Another approach would be using the setuid bit. [Edit: Looks like setuid does not work well with scripts. For explananations, see this link.]

  • A third, but very insecure method is to read the password from a password file. Warning: This is very insecure, if there's any other possibility, don't do it. And if you do it, try hiding the password file somewhere in your folder hierarchy.

    <?php
    shell_exec('sudo -u root -S bash script.sh < /home/[user]/passwordfile');
    ?>
    
  • And a fourth possibility is to use the NOPASSWD tag in the sudoers file. You should limit this power to the specific commands you need.


更改脚本权限不会将其作为root运行,而setuid在脚本上不起作用。 - Brian
不,它不会以root身份运行,但如果sudo使用的原因仅是脚本不可执行,则可以解决该问题。 至于setuid的事情,看起来你是对的。在这种情况下,请原谅我的错误信息。我找到了一个有关此主题的有用链接:http://www.faqs.org/faqs/unix-faq/faq/part4/section-7.html - Danilo Bargen
2
天啊。绝对不要保存具有根访问权限的密码!这从来都不是一个好习惯。@Brian的回答更好:不使用密码。 - cmroanirgo

5
您可以在sudoers文件中添加以下内容:
username ALL=NOPASSWD: /path/to/script

这将允许特定的用户在调用该特定脚本时无需输入密码使用sudo命令。

1
这很有道理,但有一部分让我困惑... 我应该把 username ALL=NOPASSWD: /path/to/script 这行放在哪里?我的 sudoers 文件在哪里? - JD Isaacks
1
/etc/sudoers中,通常使用visudo命令来编辑该文件。 - Daniel Egeberg

0

最好的安全方法是使用crontab。例如,将所有命令保存在数据库中,比如mysql表格中,并创建一个cronjob来读取这些mysql条目并通过shell_exec()执行。请阅读此link以获取更详细的信息。

  * * * * * killProcess.php

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接