2016-07-23 257 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. 
相關問題