Skip to content

Commit d569d15

Browse files
committed
Merge pull request #44 from gquemener/bugfix/stderr
Rely on last command exit status to raise error
2 parents 3387c69 + dc9f3da commit d569d15

File tree

2 files changed

+12
-7
lines changed

2 files changed

+12
-7
lines changed

src/Ssh/Exec.php

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
*
1010
* @author Cam Spiers <[email protected]>
1111
* @author Greg Militello <[email protected]>
12+
* @author Gildas Quéméner <[email protected]>
1213
*/
1314
class Exec extends Subsystem
1415
{
@@ -19,14 +20,18 @@ protected function createResource()
1920

2021
public function run($cmd, $pty = null, array $env = array(), $width = 80, $height = 25, $width_height_type = SSH2_TERM_UNIT_CHARS)
2122
{
23+
$cmd .= ';echo -ne "[return_code:$?]"';
2224
$stdout = ssh2_exec($this->getResource(), $cmd, $pty, $env, $width, $height, $width_height_type);
2325
$stderr = ssh2_fetch_stream($stdout, SSH2_STREAM_STDERR);
2426
stream_set_blocking($stderr, true);
2527
stream_set_blocking($stdout, true);
26-
$error = stream_get_contents($stderr);
27-
if ($error !== '') {
28-
throw new RuntimeException($error);
28+
29+
$output = stream_get_contents($stdout);
30+
preg_match('/\[return_code:(.*?)\]/', $output, $match);
31+
if ((int) $match[1] !== 0) {
32+
throw new RuntimeException(stream_get_contents($stderr), (int) $match[1]);
2933
}
30-
return stream_get_contents($stdout);
34+
35+
return preg_replace('/\[return_code:(.*?)\]/', '', $output);
3136
}
3237
}

tests/Ssh/FunctionalTests/ExecTest.php

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ public function testExecuteMultilineOutput()
4545
}
4646

4747
/**
48-
* @expectedException \RuntimeException MessageOnStdErr
48+
* @expectedException \RuntimeException
4949
*/
5050
public function testExecuteErrorOutput()
5151
{
@@ -54,9 +54,9 @@ public function testExecuteErrorOutput()
5454
$session = new Session($configuration, $authentication);
5555

5656
$exec = $session->getExec();
57-
$output = $exec->run('echo "MessageOnStdErr" > /dev/stderr');
57+
$output = $exec->run('false');
5858

5959
$this->assertEquals('', trim($output));
6060
}
6161
}
62-
62+

0 commit comments

Comments
 (0)