php - 为什么带有 ssh2_exec 的命令不会结束?

标签 php linux command debian ssh2-exec

我在使用 ssh2_exec 在我的服务器上远程运行命令时遇到问题。

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

我需要知道的是如何确保我的 ssh2_exec 脚本在继续我的其余 PHP 代码之前完全执行。

$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; 
      } 
    } 
  } 
} 

?>

最佳答案

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;
}

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

关于php - 为什么带有 ssh2_exec 的命令不会结束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37072220/

相关文章:

linux - 重命名文件并删除 shell PID 作为扩展名

linux - 如何在给定目录输入的情况下复制某些文件扩展名?

linux - 通过自己的脚本临时更改 bash 提示符

php - 从 SQL 数据库下载文件时出现错误

php - 在 codeigniter 中按 COUNT 分组使数据库错误

php - 根据单击的复选框显示值?

windows - 在输出的第一行停止 FOR/F 命令(Windows 批处理)

php - 以缩略图形式预览网站

mysql - 我如何通过Windows机器连接到Linux服务器中的mysql数据库

c - 如何从 C 程序构建用于 Unix system() 调用的字符串