How to get exit status of PHP ssh2_exec command?

1.2k Views Asked by At

I want to get the exit status of ssh2_exec command.I tried following code but it it is giving me the output of jar file but i want only the status for success or failure.How can i get that, please help.

$stream = ssh2_exec($connection, 'path of jar file');
stream_set_blocking($stream,true);
$output = ssh2_fetch_stream($stream,SSH2_STREAM_STDIO);
echo stream_get_contents($output);
2

There are 2 best solutions below

0
On

You should use stderr instead:

$output = ssh2_fetch_stream($stream,SSH2_STREAM_STDERR);

If there are no errors, it's a success.

0
On

Since version 0.13 of the SSH2 PHP extension, you can use stream_get_meta_data() to retrieve the exit staus.

With the code of your example:

$metadata = stream_get_meta_data($stream);
$exitCode = $metadata['exit_status'];