我試圖從遠程服務器的輸出流寫入文件(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