为什么使用ssh2_exec的命令不会结束?

时间:2016-05-06 12:16:31

标签: php linux command debian ssh2-exec

使用ssh2_exec远程在服务器上运行命令时出现问题。

当我使用wget或unzip时,该命令应该执行但我没有结果或只有少量文件。

我需要知道的是,在继续执行其余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; 
      } 
    } 
  } 
} 

?>

1 个答案:

答案 0 :(得分:0)

Debian可能认为这个软件包很好,因为它非常稳定(根据official site自2012-10-15以来没有变化)。但我会说它并不好。我使用以下方法:

$command = "ls -l";
$user = "user";
$host = "host";

if (! my_ssh_exec($command, $user, $host)) {
  fprintf(STDERR, "my_ssh_exec failed\n");
}


function my_ssh_exec($cmd, $host, $user) {
  $result = true;

  $desc = [
    1 => ['pipe', 'w'],
    2 => ['pipe', 'w'],
  ];

  // -tt forces TTY allocation
  $ssh_cmd = "ssh -tt $user@$host -- $cmd";

  $proc = proc_open($cmd, $desc, $pipes);

  if (! is_resource($proc)) {
    return false;
  }

  if ($error = stream_get_contents($pipes[2])) {
    fprintf(STDERR, "Error: %s\n", $error);
    $result = false;
  }
  fclose($pipes[2]);

  if ($output = stream_get_contents($pipes[1])) {
    printf("Output: %s\n", $output);
  }
  fclose($pipes[1]);

  if ($exit_status = proc_close($proc)) {
    fprintf(STDERR, "Command exited with non-zero status %d: %s\n",
      $exit_status, $cmd);
    $result = false;
  }

  return $result;
}

该脚本应该在命令行界面中运行。