【问题标题】:How to connect telnet and send command and write output into text file using php如何使用php连接telnet并发送命令并将输出写入文本文件
【发布时间】:2011-08-30 23:43:57
【问题描述】:

我需要远程登录到一个端口并发送命令并使用 PHP 将输出写入一个 txt 文件。我该怎么做?

在这个论坛有一个相同的问题名称telnet connection using PHP,但是他们有一个解决方案链接并且解决方案链接没有打开,所以我必须再次提出问题。

我还尝试了php site 的以下代码,但它没有将正确的输出保存到文本文件中。代码:

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

那么,请帮我解决问题。我如何远程登录到 localhost 端口 80 并发送命令 GET / HTTP/1.1 并将输出写入文本文件?

【问题讨论】:

    标签: php php-socket


    【解决方案1】:

    通过简单的添加,您的示例脚本当然可以将输出写入文件:

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

    再说一次,我同意 Eduard7;不手动执行请求更容易,让 PHP 为您解决它:

    <?php
    // This is much easier, I imagine?
    file_put_contents( 'output.txt', file_get_contents( 'http://localhost' ) );
    

    【讨论】:

      【解决方案2】:

      你真的想用 telnet 做这个吗?怎么样:

      echo file_get_contents("http://127.0.0.1:80");
      

      或者如果你想自定义请求,你可以使用 cURL - http://php.net/manual/en/book.curl.php

      【讨论】:

      • 夸米斯;我恭敬地不同意。虽然它“不做 telnet”,它会打开一个套接字来写出一个 GET 请求,但是 PHP 将管理套接字而不是手动进行。这是一种更简单的方法。
      • ...从问题中我认为他确实需要进行 telnet 会话,而不是简单的 http get(我认为他已经掌握了).. 我似乎无法收回我的 -1 :)
      猜你喜欢
      • 2012-10-23
      • 2011-04-23
      • 2019-11-16
      • 2016-02-14
      • 1970-01-01
      • 2013-06-28
      • 1970-01-01
      • 2021-04-04
      • 2015-06-23
      相关资源
      最近更新 更多