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条)

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记