繁体   English   中英

PHP ssh2_exec流挂起

[英]PHP ssh2_exec stream hanging

我一直试图让ssh2_exec运行并从远程主机返回响应,但无法找出执行此操作的正确方法。 我根据其他人的建议将该函数放在一起,但是一旦到达stream_get_contents($errorStream); ,该函数始终挂起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;
}

我发现如果命令的输出大小达到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);

老实说,我将使用phpseclib,这是一个纯PHP SSH实现 例如。

<?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');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM