Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get result from ssh2_exec

Tags:

php

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?

like image 333
acrobat Avatar asked Aug 23 '12 07:08

acrobat


2 Answers

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);
like image 189
acrobat Avatar answered Sep 30 '22 10:09

acrobat


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)

like image 34
TheHe Avatar answered Oct 02 '22 10:10

TheHe