• 技术文章 >php教程 >PHP源码

    使用php实现telnet功能

    PHP中文网PHP中文网2016-05-25 17:11:35原创1129

    telnet.php

    <?php
    error_reporting(-1);
    
    class Telnet {
     var $sock = NULL;
     
     function telnet($host,$port) {
      $this->sock = fsockopen($host,$port);
      socket_set_timeout($this->sock,2,0);
     }
    
     function close() {
      if ($this->sock)  fclose($this->sock);
      $this->sock = NULL;
     }
     
     function write($buffer) {
      $buffer = str_replace(chr(255),chr(255).chr(255),$buffer);
      fwrite($this->sock,$buffer);
     }
     
     function getc() {
      return fgetc($this->sock); 
     }
    
     function read_till($what) {
      $buf = '';
      while (1) {
       $IAC = chr(255);
       
       $DONT = chr(254);
       $DO = chr(253);
       
       $WONT = chr(252);
       $WILL = chr(251);
       
       $theNULL = chr(0);
     
       $c = $this->getc();
       
       if ($c === false) return $buf;
       if ($c == $theNULL) {
        continue;
       }
     
       if ($c == "1") {
        continue;
       }
    
       if ($c != $IAC) {
        $buf .= $c;
      
        if ($what == (substr($buf,strlen($buf)-strlen($what)))) {
         return $buf;
        }
        else {
         continue;
        }
       }
    
       $c = $this->getc();
       
       if ($c == $IAC) {
       $buf .= $c;
       }
       else if (($c == $DO) || ($c == $DONT)) {
        $opt = $this->getc();
        // echo "we wont ".ord($opt)."\n";
        fwrite($this->sock,$IAC.$WONT.$opt);
       }
       elseif (($c == $WILL) || ($c == $WONT)) {
        $opt = $this->getc();
        // echo "we dont ".ord($opt)."\n";
        fwrite($this->sock,$IAC.$DONT.$opt);
       }
       else {
        // echo "where are we? c=".ord($c)."\n";
       }
      }
     }
    }
    
    /*
    使用方法 示例
    $telnet = new telnet("192.168.0.1",23);
    echo $telnet->read_till("login: ");
    $telnet->write("kongxx\r\n");
    echo $telnet->read_till("password: ");
    $telnet->write("KONGXX\r\n");
    echo $telnet->read_till(":> ");
    $telnet->write("ls\r\n");
    echo $telnet->read_till(":> ");
    echo $telnet->close();
    
    */

    php入门到就业线上直播课:查看学习

    声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。

    前端(VUE)零基础到就业课程:点击学习

    清晰的学习路线+老师随时辅导答疑

    快捷开发Web应用及小程序:点击使用

    支持亿级表,高并发,自动生成可视化后台。

    专题推荐:php
    上一篇:php给现有的图片加文字水印代码 下一篇:自己动手写 PHP MVC 框架(40节精讲/巨细/新人进阶必看)

    相关文章推荐

    • ❤️‍🔥共22门课程,总价3725元,会员免费学• ❤️‍🔥接口自动化测试不想写代码?• PHP一个敏感信息过滤思路• 字符串加密解密类• 收藏PHP常用自定义函数• php读取远程服务文件• 得到PHP一个字符串的最后一个字符
    1/1

    PHP中文网