我正在尝试从远程服务器的输出流写入文件(file.txt)。输出流的内容是从远程服务器上的bash / expect脚本生成的。我不确定fwrite()
是如何工作的,然而,当我回显fget()
时,我可以看到脚本的整个输出。
有人知道fwrite()
是否只写出输出流的前几行?或者什么时候停止写作?我尝试使用while循环来连续写入但我只看到file.txt while($line = fgets($stream_out)) {fwrite($fopenText, $line);}
中的前几行。但是,当我回显fget()
时,我可以看到网页上的整个输出流,我需要将完整的输出写入我的file.txt,但这并没有。
我该如何做到这一点?
$gwUser = 'user';
$gwPwd = 'pwd';
$pathToScript1 = '/home/user/up.sh';
$pathToScript2 = '/home/user/down.sh';
if ($connection = @ssh2_connect($gateway, 22)) {
ssh2_auth_password($connection, $gwUser, $gwPwd);
if(isset($_POST['option']) && $_POST['option'] == 1) {
$stream = ssh2_exec($connection, $pathToScript1);
stream_set_blocking($stream, true);
$stream_out = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO);
$stream_err = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR);
$path = $_SERVER['DOCUMENT_ROOT'] . "/my/path/file.txt";
touch($path);
chmod($path, 0777);
$fopenText = fopen($path, "w");
while($line = fgets($stream_out)) {fwrite($fopenText, $line);} //this doesn't give me the full output stream
echo '<pre>' . "------------------------\n" . '</pre>';
while($line = fgets($stream_err)) {flush(); echo '<pre>' . $line . '</pre>';}
fclose($stream);
fclose($fopenText);
}
//I can get the the output stream this way, but this is not what i want.
if(isset($_POST['option']) && $_POST['option'] == 2) {
$stream = ssh2_exec($connection, "$pathToScript2");
stream_set_blocking($stream, true);
$stream_out = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO);
$stream_err = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR);
while($line = fgets($stream_out)) {flush(); echo '<pre>' . $line . '</pre>';}
echo '<pre>' . "------------------------\n" . '</pre>';
while($line = fgets($stream_err)) {flush(); echo '<pre>' . $line . '</pre>';}
fclose($stream);
}
}
file.txt输出:
[root@psat main]# cat file.txt
cd /home/user/
My current directory is:/home/user
./myExpectScript.sh
期望的file.txt输出(我从$_POST['option'] == 2
回复得到的信息):
cd /home/user/
My current directory is:/home/user/
./myExpectScript.sh
spawn /bin/bash
[user@gateway user]$ spawn /bin/bash
[user@gateway user]$ ./hexMsg -o 3 20000 0 0 0
??
[user@gateway user]$ /usr/local/bin/ssh " @ "
...
...
(omitted for simplicity)
答案 0 :(得分:1)
听起来好像没有返回SSH连接,因此fwrite()
循环尚未完成且文件未关闭。结果,一些输出可以被缓冲。每次写入后尝试刷新缓冲区:
while($line = fgets($stream_out)) {
fwrite($fopenText, $line);
fflush($fopenText);
}