0
我將bash腳本存儲爲db中的字符串,我需要根據用戶需求調用它。腳本應該在遠程機器上從php級別執行。我發現了以下主題:如何在遠程服務器上使用php運行本地bash腳本
兩個約ssh連接主題和調用遠程腳本:
- How to use SSH to run a shell script on a remote machine?
- https://serverfault.com/questions/241588/how-to-automate-ssh-login-with-password
而且兩種方式在PHP中使用它:
- Run Bash Command from PHP
- 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 [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
提前致謝!
什麼是你嘗試的結果嗎?遇到什麼錯誤/問題? – TenG
在兩個示例之後,我在評論「//」中寫了結果 – Krzychu
您是否可以通過檢查遠程服務器上的驗證日誌來確認SSH連接是否成功? – ghoti