doumei1203 2011-05-23 08:40
浏览 135
已采纳

如何使用php连接telnet并发送命令并将输出写入文本文件

i need to telnet to a port and send command and write the output into a txt file using PHP.How i do it?

in this forum have a same question name telnet connection using PHP but their have a solution link and the solution link is not open so i have to make the question again.

Also i try the code below from php site but it does not save the proper output into a text file.Code:

<?php
$fp = fsockopen("localhost", 80, $errno, $errstr, 30);
if (!$fp) {
    echo "$errstr ($errno)<br />
";
} else {
    $out = "GET / HTTP/1.1
";
    $out .= "Host: localhost
";
    $out .= "Connection: Close

";
    fwrite($fp, $out);
    while (!feof($fp)) {
        echo fgets($fp, 128);
    }
    fclose($fp);
}
?>

So,please help me to solve the problem.How i telnet to localhost port 80 and send command GET / HTTP/1.1 and write the output into a text file?

  • 写回答

2条回答 默认 最新

  • douxian5076 2011-05-23 09:08
    关注

    With a simple additition, your example script can write the output to a file, of course:

    <?php
    $fp = fsockopen("localhost", 80, $errno, $errstr, 30);
    if (!$fp) {
        echo "$errstr ($errno)<br />
    ";
    } else {
        $out = "GET / HTTP/1.1
    ";
        $out .= "Host: localhost
    ";
        $out .= "Connection: Close
    
    ";
        fwrite($fp, $out);
    
        $output = '';
        while (!feof($fp)) {
            $output .= fgets($fp, 128);
        }
    
        fclose($fp);
        file_put_contents( 'output.txt', $output );
    }
    

    Then again, I agree with Eduard7; it's easier not to do the request manually and just let PHP solve it for you:

    <?php
    // This is much easier, I imagine?
    file_put_contents( 'output.txt', file_get_contents( 'http://localhost' ) );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 ue5运行的通道视频都会有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数