Reputation: 25336
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;
}
Upvotes: 0
Views: 1857
Reputation: 37
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);
Upvotes: 1
Reputation: 16792
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');
Upvotes: 0