【问题标题】:PHP ssh2_exec stream hangingPHP ssh2_exec 流挂起
【发布时间】:2014-06-26 14:58:36
【问题描述】:

我一直试图让ssh2_exec 运行并从远程主机返回响应,但无法找出正确的方法来执行此操作。我根据其他人的推荐一起使用了这个函数,但是一旦到达stream_get_contents($errorStream);,这个函数总是挂起。

我正在运行的命令是ls -l,所以它应该执行得非常快。

public function exec($command) 
{
    $stream = ssh2_exec($this->ssh, $command);

    if (! $stream) {
        throw new exception('Could not open shell exec stream');
    }
    $errorStream = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR);

    stream_set_blocking($errorStream, true);
    stream_set_blocking($stream, true);

    $err      = stream_get_contents($errorStream);
    $response = stream_get_contents($stream);

    @fclose($errorStream);
    @fclose($stream);

    if ($err) {
        throw new exception($err);
    }

    return $response;
}

【问题讨论】:

    标签: php ssh libssh2


    【解决方案1】:

    我发现如果命令的输出大小达到 64KB(正是我的 Linux 开发盒上的那个数字),函数 ssh2_exec() 将挂起。

    一种避免的方法是使用:stream_set_timeout()

    $stream = ssh2_exec($this->ssh, $command);
    
    if (! $stream) {
        throw new exception('Could not open shell exec stream');
    }
    
    stream_set_timeout($stream, 10);
    

    【讨论】:

      【解决方案2】:

      老实说,我会使用phpseclib, a pure PHP SSH implementation。例如。

      <?php
      include('Net/SSH2.php');
      
      $ssh = new Net_SSH2('www.domain.tld');
      if (!$ssh->login('username', 'password')) {
          exit('Login Failed');
      }
      
      echo $ssh->exec('ls -l');
      

      【讨论】:

        猜你喜欢
        • 2015-01-30
        • 1970-01-01
        • 2015-10-22
        • 1970-01-01
        • 2019-02-15
        • 2011-08-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多