从 PHP 脚本执行 shell 脚本 [英] Executing a shell script from a PHP script

查看:65
本文介绍了从 PHP 脚本执行 shell 脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从 PHP 脚本执行系统上存在的 Bash 脚本.我在系统上有两个脚本.其中一个是名为 client.php 的 PHP 脚本存在于 /var/www/html 中,另一个是名为 testscript 的 Bash 脚本存在在 /home/testuser.

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 的用户/组与您的网络文件相同.例如,如果您的 client.phpapache: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);
    ?>  

如果你真的想从网络服务器以 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 执行 root 命令

这篇关于从 PHP 脚本执行 shell 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆