2024 年 PHP Conference Japan

ssh2_fetch_stream

(PECL ssh2 >= 0.9.0)

ssh2_fetch_stream擷取擴充資料流

描述

ssh2_fetch_stream(資源 $channel, int $streamid): 資源

擷取與 SSH2 通道流關聯的替代子流。SSH2 協定目前只定義了一個子流,STDERR,其子流 ID 為 SSH2_STREAM_STDERR (定義為 1)。

參數

channel

streamid

一個 SSH2 通道流。

回傳值

返回請求的流資源。

範例

範例 #1 開啟 shell 並取得與其相關聯的 stderr 串流

<?php
$connection
= ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');

$stdio_stream = ssh2_shell($connection);
$stderr_stream = ssh2_fetch_stream($stdio_stream, SSH2_STREAM_STDERR);
?>

另請參閱

新增註解

使用者貢獻的註解 4 則註解

ingo at baab dot de
4 年前
除了 Dennis K. 13 年前的最後一篇文章之外,我修正了兩個錯字(常數 SSH2_STREAM_STDIO 拼寫錯誤)並移除了一些(過多的)括號 - 這段程式碼可以運作

<?php
$stdout_stream
= ssh2_exec($connection, "lsssss -la");

$sio_stream = ssh2_fetch_stream($stdout_stream, SSH2_STREAM_STDIO);
$err_stream = ssh2_fetch_stream($stdout_stream, SSH2_STREAM_STDERR);

stream_set_blocking($sio_stream, true);
stream_set_blocking($err_stream, true);

$result_dio = stream_get_contents($sio_stream);
$result_err = stream_get_contents($err_stream);

echo
'stderr: ' . $result_err;
echo
'stdio : ' . $result_dio;
?>
Ricardo Striquer (ricardophp yohoocombr)
17 年前
我有一個朋友使用了這些函式,但他無法使用 ssh2_fetch_stream 函式。首先我從 webmaster at spectreanime dot com 取得了 ssh2_shell 的範例,但這個函式在他的範例中無法運作,我相信這是因為他使用 fwrite 而不是 ssh2_shell 或 ssh2_exec 來執行指令。

以下範例可在命令列下執行,並且功能完整。請注意,我按照 spectreanime.com 網站管理員的建議添加了 sleep 函式。

<?php
echo "SSH 連線 ";
if (!(
$connection=@ssh2_connect("69.69.69.69", 22))) {
echo
"[失敗]\n";
exit(
1);
}
echo
"[成功]\n驗證中 ";

if (!@
ssh2_auth_password($connection,"root","您的密碼")) {
echo
"[失敗]\n";
exit(
1);
}
echo
"[成功]\n";

$stdout_stream = ssh2_exec($connection, "/bin/lssss -la /tmp");
sleep(1);
$stderr_stream = ssh2_fetch_stream($stdout_stream, SSH2_STREAM_STDERR);

echo
"發現錯誤!\n------------\n";
while(
$line = fgets($stderr_stream)) { flush(); echo $line."\n"; }
echo
"------------\n";

while(
$line = fgets($stdout_stream)) { flush(); echo $line."\n";}

fclose($stdout_stream);
?>
hexer
16 年前
我已成功在 PHP4 中使用 fgets

範例

<?php
$stderr
= fgets(ssh2_fetch_stream($channel, SSH2_STREAM_STDERR), 8192);

$str = fgets(ssh2_fetch_stream($channel, SSH2_STREAM_STDIO), 8192);
?>
Dennis K.
17 年前
補充 Ricardo Striquer 上一篇的發文

只要使用 stream_set_blocking() 阻塞串流,就不需要使用 sleep() 函式讓程式碼休眠...

<?php
stdout_stream
= ssh2_exec($connection, "/bin/lssss -la /tmp");

$err_stream = ssh2_fetch_stream($stdout_stream, SSH2_STREAM_STDERR);

$dio_stream = ssh2_fetch_stream($stdout_stream, SSH2_STREAM_STDDIO);

stream_set_blocking($err_stream, true);
stream_set_blocking($dio_stream, true);

$result_err = stream_get_contents($err_stream));
$result_dio = stream_get_contents($dio_stream));
?>
To Top