【问题标题】:How to execute a shell script on a remote linux machine using php如何使用 php 在远程 linux 机器上执行 shell 脚本
【发布时间】:2016-04-02 20:00:55
【问题描述】:

我在 /home/ 目录中 IP:192.168.1.1 的远程 ubuntu 机器上有一个 shell 脚本 test.sh,我的 apache2 和 php 安装在 IP:192.168.1.2 的 ubuntu 机器上。

我需要从网络服务器机器上执行远程节点上的 shell 脚本,有什么方法可以使用 php 脚本来做到这一点吗?

【问题讨论】:

标签: php linux bash shell ubuntu


【解决方案1】:

我认为您可以做的快速方法(但不是安全方法)是在另一台服务器上设置一个 Web 服务器,并在那里创建一个 PHP 脚本来调用 bash 脚本。所以在服务器 192.168.1.1 上调用脚本 php。

但我认为最好的方法是,当你想调用这是脚本时,将请求放入某个队列(可能在数据库中),在另一台服务器上创建 Python 或 PHP 脚本来使用它排队并运行 bash 脚本。这个 Python/PHP 脚本将通过 Cron 执行。因此,通过这种方式,您无法像第一个解决方案那样直接调用脚本。这是安全的方式。

【讨论】:

    【解决方案2】:

    我最近发布了一个项目,它允许 PHP 获取并与真正的 Bash shell 交互,如果需要,可以通过 SSH。在这里获取:https://github.com/merlinthemagic/MTS

    我可以建议触发个别命令而不是脚本。这样您就可以处理返回,而无需在 bash 中构建异常处理。

    下载后您只需使用以下代码:

        //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.
    

    【讨论】:

      最近更新 更多