PHP ssh2_exec通道退出状态?

时间:2012-05-07 07:47:08

标签: php ssh pecl

好的,所以pecl ssh2应该是libssh2的包装器。 libssh2有libssh2_channel_get_exit_status。有没有办法获取这些信息?

我需要:
-stdout
-STDERR
-EXIT STATUS

我得到的只是退出状态。当ssh出现时,很多人都会在phplibsec附近投掷,但是我认为没有办法让stderr或者频道退出状态:/有没有人能够获得所有三个?

2 个答案:

答案 0 :(得分:8)

所以,首先要做的是:
不,他们没有实现libssh2_channel_get_exit_status。为什么?超越我。

这是id做了什么:

$command .= ';echo -e "\n$?"'

我补充了换行符和$的回声?在每个命令的结尾我执行。瘦长?是。但似乎效果相当不错。然后我将其关闭到$ returnValue并在stdout结束时删除所有换行符。也许有一天会得到频道的退出状态得到支持,几年之后它就会出现在发行版中。就目前而言,这已经足够了。当您运行30多个远程命令来填充复杂的远程资源时,这比为每个命令设置和拆除ssh会话要好得多。

答案 1 :(得分:7)

我试图改进Rapzid的答案。为了我的目的,我在php对象中包装了ssh2并实现了这两个函数。它允许我使用合理的异常捕获来处理ssh错误。

function exec( $command )
{
    $result = $this->rawExec( $command.';echo -en "\n$?"' );
    if( ! preg_match( "/^(.*)\n(0|-?[1-9][0-9]*)$/s", $result[0], $matches ) ) {
        throw new RuntimeException( "output didn't contain return status" );
    }
    if( $matches[2] !== "0" ) {
        throw new RuntimeException( $result[1], (int)$matches[2] );
    }
    return $matches[1];
}

function rawExec( $command )
{
    $stream = ssh2_exec( $this->_ssh2, $command );
    $error_stream = ssh2_fetch_stream( $stream, SSH2_STREAM_STDERR );
    stream_set_blocking( $stream, TRUE );
    stream_set_blocking( $error_stream, TRUE );
    $output = stream_get_contents( $stream );
    $error_output = stream_get_contents( $error_stream );
    fclose( $stream );
    fclose( $error_stream );
    return array( $output, $error_output );
}
相关问题