我使用的是phpseclib,本质上我要做的是,每当exec流从流中接收到任何数据时,都要将数据写入文件(而不是像使用fgets那样等待数据显示并同时挂起),这样我就可以在一段时间内将数据写入需要写入的流。
伪代码:
while stream isn't null:
check for incoming data from the stream, if there is none, then continue to the next part of loop
if there is data, then write it to file x.txt
write any data into the socket that needs to be written.
我将如何着手实施这一点?我试过几种方法,但似乎都不起作用。
Net_SSH2::exec()
的$callback
参数似乎可以满足您的需要。例如
function packet_handler($str)
{
global $fp;
fputs($fp, $str);
}
$ssh->exec('ping 127.0.0.1', 'packet_handler');
?>
如果做不到。。。也许你可以做这样的事情(未经测试):
$ssh->setTimeout(.1);
$ssh->exec('command');
while ($ssh->isConnected()) {
if (stream_select(...)) {
fputs($fp, $ssh->read());
}
$ssh->write(...);
}
你可能也需要一个PTY。
或执行类似。。。
$tmp = $cn->exec($cmd, false);
$cn->setTimeout(10);
while (<some conditional>) {
$tmp = $cn->_get_channel_packet(NET_SSH2_CHANNEL_EXEC);
switch (true) {
case === true:
# Completed (or timed out if you are using setTimeout)
if ($cn->is_timeout) {
# Timed out
break; # Go through loop again?
}
break 2;
case === false:
# Disconnect or error
break 2;
default:
# write to your file
break;
}
# Other stuff to do before going back around
}
它将暂停长达10秒的等待,然后重新控制。这取决于你想要完成什么。