나는 Rapzid의 답변을 좀더 개선하려고 노력했다. 내 목적을 위해 PHP 객체에 ssh2를 래핑하고이 두 함수를 구현했습니다. sane exception catch를 사용하여 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);
}
명령이 'exit 1'이면 에코가 실행되지 않습니다. '$ command = '('. $ command. '); echo -e "\ n $?"''더 좋을 수도 있습니다. – Jesse