16

I have a script that makes a SSH connection to a server (this works fine). Now I want to execute a command and echo the result I get from this command.

So I do this:

$stream = ssh2_exec($conn, 'php -v');

but I can't get it to show the response, var_dump returns resource(3) of type (stream).

I have tried to use:

$stream = ssh2_exec($conn, 'php -v');
$stream_out = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR);

but the $stream_out returns an empty string.

So is it possible to print the response as result of the script?

Florent
  • 12,310
  • 10
  • 49
  • 58
acrobat
  • 2,179
  • 2
  • 27
  • 35

3 Answers3

50

Ok i found the solution, so i post it for future reference

So to output the result of a command executed by ssh2_exec you should use following code setup

$stream = ssh2_exec($conn, 'php -v');
stream_set_blocking($stream, true);
$stream_out = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO);
echo stream_get_contents($stream_out);
acrobat
  • 2,179
  • 2
  • 27
  • 35
  • I believe the call to ssh2_fetch_stream is unnecessary -- you could just use $stream. – S. Imp Jul 26 '17 at 22:41
  • 1
    You can get the IO output of the stream without calling "ssh2_fetch_stream" but you cannot get the STDERR output. – Nonetallt Dec 04 '17 at 12:56
2

add:

echo stream_get_contents($stream);

the result is the STREAM and you have to fetch it's contents first...

stream-fetch is only for fetching alternate sub-streams... (afaik)

TheHe
  • 2,933
  • 18
  • 22
0

The following code should get the error message written to stderr, but if the call to stream_get_contents() for stdout is run first, the subsequent call for stderr won't return anything.

If the order of the statements is reversed, the call for stderr will return any errors and call for stdout will return nothing

https://www.php.net/manual/en/function.ssh2-exec.php#99089

Guest
  • 1
  • 1