[英]How to call shell script from php that requires SUDO?
I have a file that is a bash script that requires SUDO to work. 我有一个文件,它是需要SUDO才能工作的bash脚本。
I can run it from the command line using SUDO but I will be prompted to put in the SUDO password. 我可以使用SUDO从命令行运行它,但系统会提示我输入SUDO密码。
I want to run this script from php via shell_exec
but I if I call SUDO, its not like a command line where I can be prompted for the password. 我想通过shell_exec
从php运行此脚本,但是如果我调用SUDO,它就不像命令行,在命令行中可以提示我输入密码。 Is there a way to pass the password for sudo with the sudo call? 有没有办法通过sudo调用传递sudo的密码?
How can I do this? 我怎样才能做到这一点?
Edit the sudoers file (with visudo
) and add a rule that allows the web server user to run the command without a password. 编辑sudoers文件(使用visudo
),并添加一条规则,该规则允许Web服务器用户无需密码即可运行命令。 For example: 例如:
www-data ALL=NOPASSWD: /path/to/script
There are various solutions for this problem. 有各种解决此问题的方法。
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). 首先,如果您想要sudo的原因仅仅是权限问题,请考虑更改脚本权限(请参阅我在上述问题中添加的注释)。
Another approach would be using the
setuid bit .
另一种方法是使用
setuid位 。
[Edit: Looks like setuid does not work well with scripts. [编辑:看起来setuid在脚本中不能很好地工作。 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. 第四种可能性是在sudoers文件中使用NOPASSWD标记 。 You should limit this power to the specific commands you need. 您应该将此功能限制为所需的特定命令。
You can add something like this to your sudoers
file: 您可以将以下内容添加到您的sudoers
文件中:
username ALL=NOPASSWD: /path/to/script
This will allow that particular user to call sudo
on that particular script without being prompted for a password. 这将允许该特定用户在该特定脚本上调用sudo
而不提示您输入密码。
The best secure method is to use the crontab. 最好的安全方法是使用crontab。 ie Save all your commands in a database say, mysql table and create a cronjob to read these mysql entreis and execute via shell_exec(). 将所有命令保存在数据库中,例如mysql表中,并创建一个cronjob来读取这些mysql entreis并通过shell_exec()执行。 Please read this link for more detailed information. 请阅读此链接以获取更多详细信息。
* * * * * killProcess.php
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.