2012-05-07 59 views
5

好吧,所以pecl ssh2被认为是libssh2的包装。 libssh2具有libssh2_channel_get_exit_status。有什么方法可以获取这些信息吗?PHP ssh2_exec通道退出状态?

我需要:
-stdout
-STDERR
-exit状态

我得到的所有,但退出状态。当ssh出现时,很多人都会抛出phplibsec,但是我看不出任何方式让stderr或者频道退出状态退出:/有没有人能够获得这三个?

回答

6

所以,第一件事是第一件事:
不,他们没有实现libssh2_channel_get_exit_status。为什么?超越我。

这里是ID做:

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

我补习班的$换行和回声?到我执行的每个命令的末尾。瘦长?是。但它看起来工作得很好。然后我把它放到$ returnValue中,并将所有新行从标准输出结束。也许有一天会获得渠道的退出状态,几年之后它将在发行版中发布。现在,这已经足够好了。当您运行30+个远程命令来填充复杂的远程资源时,这比为每个命令设置和拆除ssh会话要好得多。

+1

如果命令是'exit 1',回声将不会运行。 '$ command ='('。$ command。'); echo -e“\ n $?”“''可能会更好。 – Jesse

5

我试图改进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); 
}