我试图从远程服务器的输出流写入文件(file.txt)。输出流的内容是从远程服务器上的bash/expect脚本生成的。我不知道如何fwrite()
工作,但是,当我回应fget()
我可以看到脚本的整个输出。PHP从输出流写入文件仅写入前几行
有谁知道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的输出:
[[email protected] 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
[[email protected] user]$ spawn /bin/bash
[[email protected] user]$ ./hexMsg -o 3 20000 0 0 0
??
[[email protected] user]$ /usr/local/bin/ssh " @ "
...
...
(omitted for simplicity)
'$ _ POST [ '选项'] == 1',同时'$ _ POST [ '选项'] == 2'使用'$ pathToScript2使用'$ pathToScript1' '所以他们正在运行不同的shell脚本。你确定输出应该是一样的吗? – neuromatter
@neuromatter对不起,输出不重要,我得到了这部分工作,因为即使我调用相同的脚本,它'fwrite' file.txt只显示前几行,而我的'选项== 2'会回应我所需要的。我只是想让流完全写入file.txt,这是我遇到问题的地方。现在让我们假设两个脚本都做同样的事情。 – kkmoslehpour
你看到'-----'行吗?如果没有,SSH连接可能不会退出,所以'fwrite()'循环尚未完成。 – Barmar