PHP ssh2_exec stream hanging

2019-08-19 05: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;
}

标签: php ssh libssh2
2条回答
劫难
2楼-- · 2019-08-19 05:55

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);
查看更多
Juvenile、少年°
3楼-- · 2019-08-19 06:06

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');
查看更多
登录 后发表回答