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;
}
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()
Honestly, I would use phpseclib, a pure PHP SSH implementation. eg.