Skip to content

Commit

Permalink
Merge pull request #44 from gquemener/bugfix/stderr
Browse files Browse the repository at this point in the history
Rely on last command exit status to raise error
  • Loading branch information
Herzult committed Mar 17, 2015
2 parents 3387c69 + dc9f3da commit d569d15
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 7 deletions.
13 changes: 9 additions & 4 deletions src/Ssh/Exec.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
*
* @author Cam Spiers <camspiers@gmail.com>
* @author Greg Militello <junk@thinkof.net>
* @author Gildas Quéméner <gildas.quemener@gmail.com>
*/
class Exec extends Subsystem
{
Expand All @@ -19,14 +20,18 @@ protected function createResource()

public function run($cmd, $pty = null, array $env = array(), $width = 80, $height = 25, $width_height_type = SSH2_TERM_UNIT_CHARS)
{
$cmd .= ';echo -ne "[return_code:$?]"';
$stdout = ssh2_exec($this->getResource(), $cmd, $pty, $env, $width, $height, $width_height_type);
$stderr = ssh2_fetch_stream($stdout, SSH2_STREAM_STDERR);
stream_set_blocking($stderr, true);
stream_set_blocking($stdout, true);
$error = stream_get_contents($stderr);
if ($error !== '') {
throw new RuntimeException($error);

$output = stream_get_contents($stdout);
preg_match('/\[return_code:(.*?)\]/', $output, $match);
if ((int) $match[1] !== 0) {
throw new RuntimeException(stream_get_contents($stderr), (int) $match[1]);
}
return stream_get_contents($stdout);

return preg_replace('/\[return_code:(.*?)\]/', '', $output);
}
}
6 changes: 3 additions & 3 deletions tests/Ssh/FunctionalTests/ExecTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public function testExecuteMultilineOutput()
}

/**
* @expectedException \RuntimeException MessageOnStdErr
* @expectedException \RuntimeException
*/
public function testExecuteErrorOutput()
{
Expand All @@ -54,9 +54,9 @@ public function testExecuteErrorOutput()
$session = new Session($configuration, $authentication);

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

$this->assertEquals('', trim($output));
}
}


0 comments on commit d569d15

Please sign in to comment.