简体   繁体   English

如何使用PHP在远程Linux机器上执行Shell脚本

[英]How to execute a shell script on a remote linux machine using php

I have a shell script test.sh on a remote ubuntu machine with IP:192.168.1.1 in the/home/ directory and I have my apache2 and php installed in ubuntu machine with IP:192.168.1.2. 我在/ home /目录中IP:192.168.1.1的远程ubuntu机器上有一个shell脚本test.sh,并且我在IP:192.168.1.2的ubuntu机器上安装了我的apache2和php。

I need to execute the shell script on remote node from webserver machine, is there any way I can do that using a php script? 我需要从Web服务器上的远程节点上执行Shell脚本,有什么办法可以使用php脚本来做到这一点?

I think the fast way you can do (but not the secure way) is set up an Web server on the another server, and create a PHP script there to call the bash script. 我认为您可以执行的快速方法(但不是安全方法)是在另一台服务器上设置Web服务器,然后在其中创建PHP脚本以调用bash脚本。 So on the server 192.168.1.1 you call the script php. 因此,在服务器192.168.1.1上,您将脚本称为php。

But i think the best way to do that, is when you want call this is script, put the request in some queue (could be on the database), on the other server you create a Python or PHP script to consume this queue and run the bash script. 但我认为最好的方法是在脚本中调用该请求,将请求放入某个队列(可能在数据库中),在另一台服务器上创建Python或PHP脚本以使用此队列并运行bash脚本。 This Python/PHP script will be executed via Cron. 此Python / PHP脚本将通过Cron执行。 So in this way you are not able to call the script directly like the first solution. 因此,以这种方式,您将无法像第一个解决方案那样直接调用脚本。 This is the secure way. 这是安全的方法。

I recently published a project that allows PHP to obtain and interact with a real Bash shell, through SSH if needed. 我最近发布了一个项目,该项目允许PHP根据需要通过SSH获取并与真实的Bash shell进行交互。 Get it here: https://github.com/merlinthemagic/MTS 在这里获取它: https : //github.com/merlinthemagic/MTS

May i suggest triggering the induvidual commands rather than a script. 我可以建议触发单个命令而不是脚本。 That way you can handle the return without having to build exception handling in bash. 这样,您就可以处理返回值,而不必在bash中构建异常处理。

After downloading you would simply use the following code: 下载后,您只需使用以下代码:

    //get a shell
    $shell = \MTS\Factories::getDevices()->getRemoteHost('192.168.1.1')->getShellBySsh('username', 'secretPassword');

    //trigger your script
    $return1  = $shell->exeCmd('/home/test.sh');

    echo $return1;//the return from your script.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM