我在遠程使用ssh2_exec在服務器上運行命令時出現問題。爲什麼使用ssh2_exec的命令不會結束?
當我使用wget或解壓縮時,該命令應該執行,但我得不到結果或只有幾個文件。
我需要知道的是,在繼續執行我的其他PHP代碼之前,我可以確定我的ssh2_exec腳本將完全執行。
$stream =ssh2_exec($connection, 'cd /home; wget http://domain.com/myfile.zip; unzip myfile.zip; rm myfile.zip');
在此先感謝!
編輯:我發現腳本,如何得到命令的結果?
<?php
$ip = 'ip_address';
$user = 'username';
$pass = 'password';
$connection = ssh2_connect($ip);
ssh2_auth_password($connection,$user,$pass);
$shell = ssh2_shell($connection,"bash");
//Trick is in the start and end echos which can be executed in both *nix and windows systems.
//Do add 'cmd /C' to the start of $cmd if on a windows system.
$cmd = "echo '[start]';your commands here;echo '[end]'";
$output = user_exec($shell,$cmd);
fclose($shell);
function user_exec($shell,$cmd) {
fwrite($shell,$cmd . "\n");
$output = "";
$start = false;
$start_time = time();
$max_time = 2; //time in seconds
while(((time()-$start_time) < $max_time)) {
$line = fgets($shell);
if(!strstr($line,$cmd)) {
if(preg_match('/\[start\]/',$line)) {
$start = true;
}elseif(preg_match('/\[end\]/',$line)) {
return $output;
}elseif($start){
$output[] = $line;
}
}
}
}
?>
你能提供你正在使用的命令嗎?我們需要更多信息才能提供幫助。 – mtrueblood
我已經編輯帖子,:) – SarahG
我認爲你的命令可能是異步運行的,這就是爲什麼你沒有得到你正在尋找的結果。 – mtrueblood