首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么使用ssh2_exec的命令不结束?

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

Stack Overflow用户
提问于 2016-05-06 20:16:31
回答 1查看 805关注 0票数 0

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

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

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

代码语言:javascript
复制
$stream =ssh2_exec($connection, 'cd /home; wget http://domain.com/myfile.zip; unzip myfile.zip; rm myfile.zip');

提前感谢!

编辑:我找到脚本了,如何获取命令的结果?

代码语言:javascript
复制
<?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; 
      } 
    } 
  } 
} 

?>
EN

回答 1

Stack Overflow用户

发布于 2016-05-06 21:11:01

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

代码语言:javascript
复制
$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;
}

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37072220

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档