PHP ssh2_exec stream hanging

戏子无情 提交于 2019-12-11 15:12:36

问题


I've been trying to get ssh2_exec to run and return the response from the remote host, but cannot figure out the proper way to do this. I thew this function together based on what others have recommended, but the function always hangs once it gets to stream_get_contents($errorStream);.

The command I'm running is ls -l so it should be executing very quickly.

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

回答1:


I found that the function ssh2_exec() will hang if the size of the output of the command reaches to 64KB (exactly that number on my Linux dev box).

One way to avoid is to use: 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:


Honestly, I would use phpseclib, a pure PHP SSH implementation. eg.

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


来源:https://stackoverflow.com/questions/14571523/php-ssh2-exec-stream-hanging

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!