2016-07-23 187 views
0

我将bash脚本存储为db中的字符串,我需要根据用户需求调用它。脚本应该在远程机器上从php级别执行。我发现了以下主题:如何在远程服务器上使用php运行本地bash脚本

两个约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_exechttp://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 [email protected] 'bash -s' < test"); 
chdir($old_path); 

or 

$old_path = getcwd(); 
chdir('/path_to_script_directory'); 
$output = shell_exec("ssh [email protected] 'bash -s' < ".$script); 
chdir($old_path); 
//result => output = null 

作为例子上面我用“测试”脚本尝试了两个例子pt和字符串脚本($ script变量)。第二种选择是由我优先。两种情况都包含简单的脚本:

#!/bin/bash 

ifconfig 

提前致谢!

+0

什么是你尝试的结果吗?遇到什么错误/问题? – TenG

+0

在两个示例之后,我在评论“//”中写了结果 – Krzychu

+0

您是否可以通过检查远程服务器上的验证日志来确认SSH连接是否成功? – ghoti

回答

0

这里是一个项目,会给你一个远程服务器上的真正的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. 
相关问题