从PHP脚本执行Shell脚本 [英] Executing a shell script from a PHP script
问题描述
我想从PHP脚本执行系统上存在的Bash脚本.我的系统上有两个脚本.其中一个是在/var/www/html
上出现的名为client.php
的PHP脚本,另一个是在/home/testuser
上出现的名为testscript
的Bash脚本.
I want to execute a Bash script present on the system from a PHP script. I have two scripts present on the system. One of them is a PHP script called client.php
present at /var/www/html
and the other is a Bash script called testscript
present at /home/testuser
.
我的client.php脚本看起来像
My client.php script looks like
<?php
$message=shell_exec("/home/testuser/testscript 2>&1");
print_r($message);
?>
我的测试脚本看起来像
#!/bin/bash
echo "Testscript run succesful"
当我在终端上执行以下操作
When i do the following on terminal
php client.php
我在终端上得到以下输出
I get the following output on terminal
Testscript run successful
但是当我在
http://serverdomain/client.php
我得到以下输出
sh: /home/testuser/testscript: Permission denied
即使执行了chmod + x testscript,我仍然收到此错误.
我如何从浏览器中获取它?请帮忙.
I get this error even after I did chmod +x testscript.
How do I get it to work from the browser? Please help.
推荐答案
我将在WWW文件夹下的某个目录中有一个名为scripts的目录,因此它不能从Web上访问,但可以通过PHP访问.
I would have a directory somewhere called scripts under the WWW folder so that it's not reachable from the web but is reachable by PHP.
例如/var/www/scripts/testscript
确保testscript
的用户/组与您的Web文件相同.例如,如果您的client.php
由apache:apache
拥有,则使用chown
将bash脚本更改为相同的用户/组.您可以通过执行ls -al
来查找您的client.php
和Web文件所拥有的文件.
Make sure the user/group for your testscript
is the same as your webfiles. For instance if your client.php
is owned by apache:apache
, change the bash script to the same user/group using chown
. You can find out what your client.php
and web files are owned by doing ls -al
.
然后运行
<?php
$message=shell_exec("/var/www/scripts/testscript 2>&1");
print_r($message);
?>
如果您真的想从Web服务器上以root用户身份运行文件,则可以在下面尝试使用此二进制包装程序.签出此解决方案,以完成您想做的相同事情.
If you really want to run a file as root from a webserver you can try this binary wrapper below. Check out this solution for the same thing you want to do.
这篇关于从PHP脚本执行Shell脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!