【问题标题】:How to run local bash script on remote server using php如何使用 php 在远程服务器上运行本地 bash 脚本
【发布时间】:2016-07-23 19:50:26
【问题描述】:

我将 bash 脚本作为字符串存储在 db 中,我需要根据用户需求调用它。脚本应该从 php 级别在远程机器上执行。我找到了以下主题:

关于ssh连接和调用远程脚本的两个话题:

  1. How to use SSH to run a shell script on a remote machine?
  2. https://serverfault.com/questions/241588/how-to-automate-ssh-login-with-password

以及在php中的两种使用方式:

  1. Run Bash Command from PHP
  2. get result from ssh2_exec , http://php.net/manual/en/function.ssh2-exec.php

我尝试在我的 symfony2 应用程序中使用以下代码:

第一次尝试:

$connection = ssh2_connect('IP_ADDRESS', 22);
ssh2_auth_password($connection, 'user', 'password');
$stream = ssh2_exec($connection, "'bash -s' < ".$script);
stream_set_blocking($stream, true);
$stream_out = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO);
$output = stream_get_contents($stream_out);
//result => output = empty string

第二:

$old_path = getcwd();
chdir('/path_to_script_directory');
$output = shell_exec("ssh user@server 'bash -s' < test");
chdir($old_path);

or

$old_path = getcwd();
chdir('/path_to_script_directory');
$output = shell_exec("ssh user@server 'bash -s' < ".$script);
chdir($old_path);
//result => output = null

在上面的例子中,我用“test”脚本和字符串脚本($script 变量)尝试了两种情况。我更喜欢第二种选择。两种情况都包含简单的脚本:

#!/bin/bash

ifconfig

提前谢谢你!

【问题讨论】:

  • 您的尝试结果如何?遇到了哪些错误/问题?
  • 我在两个示例之后的注释“//”中写了结果
  • 您能否通过查看远程服务器上的身份验证日志来确认您的 SSH 连接是否成功?

标签: php bash ssh


【解决方案1】:

这是一个可以在远程服务器上为您提供真正的 bash shell 的项目:https://github.com/merlinthemagic/MTS

安装并运行以下命令:

//login to the remote server and get a shell:

$shellObj       = \MTS\Factories::getDevices()->getRemoteHost('ip_address')->setConnectionDetail('username', 'password')->getShell();

//rather than executing your script, just run the command:

$returnData = $shellObj->exeCmd("ifconfig");

echo $returnData; //string containing the interface config of the remote server.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-11
    • 1970-01-01
    • 2018-03-14
    • 2013-12-28
    • 2011-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多