清空PHP SSH2流内容,即使使用stream_set_blocking?

时间:2009-10-10 18:18:47

标签: php ssh stream

我正在研究一种工具,它使用PECL SSH2扩展通过SSH2从远程主机读取iptables配置。我能够成功建立与主机的连接,验证和执行命令。我遇到的麻烦有时候流不包含任何数据。

 /**
  * Load the current firewall configuration
  * @return bool
  */
 public function loadRules() {
  $stream = ssh2_exec($this->connection,"~/iptsave;");
  stream_set_blocking($stream,true);
  $iptablesSave = stream_get_contents($stream);
  if(empty($iptablesSave)) {
   return false;
   }
  parent::restore($iptablesSave);
  return true;
  }

大约25%的时间,loadRules()返回false,即使连接到locahost而不是远程系统也是如此。我能够通过将ssh2_exec调用更改为

来解决此问题
$stream = ssh2_exec($this->connection,"~/iptsave; sleep .5");

但我担心出现问题。

3 个答案:

答案 0 :(得分:1)

phpSecLib可以提供帮助:

根据this post,它总是返回输出,与ssh2.so不同。

答案 1 :(得分:-1)

我在这里遇到同样的问题。不知何故,您需要设置延迟以获取流的结果。

您可以这样做,但您也可以在sleep(1)功能之后设置stream_set_block($stream, true)。 您可以尝试usleep()功能。尚未尝试过

答案 2 :(得分:-1)

可能会解决这个问题:

$stream = ssh2_exec($this->connection,"~/iptsave;");
stream_set_blocking($stream,true);
$stream_out = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO);
$iptablesSave = stream_get_contents($stream);