我在远程使用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