PHP如何登录连接TELNET并执行交换机命令类 图文教程

今天开发的时候需要登录交换机执行命令,下面我们记录一下php的class类来完成。

<?php 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";             }         }     } }

这里需要使用 fsockopen 方法:

(PHP 4, PHP 5, PHP 7)
fsockopen — 打开一个网络连接或者一个Unix套接字连接

调用使用方法:

<?php $telnet = new telnet("ip", 'port'); echo $telnet->read_till("login: "); $telnet->write("usern");//telnet用户名 echo $telnet->read_till("password: "); $telnet->write("passwdn");//telnet密码 echo $telnet->read_till(">"); //echo $telnet->read_till(":> "); $telnet->write("dis devn");//执行命令1 echo $telnet->read_till(">"); $telnet->write("dis devn");//执行命令2 echo $telnet->read_till(">"); // TODO  echo $telnet->close();//关闭连接

腾讯云限时秒杀【点击购买】

搬瓦工,CN2高速线路,1GB带宽,电信联通优化KVM,延迟低,速度快,建站稳定,搬瓦工BandwagonHost VPS优惠码BWH26FXH3HIQ,支持<支付宝> 【点击购买】!

Vultr$3.5日本节点,512M内存/500G流量/1G带宽,电信联通优化,延迟低,速度快【点击购买】!

阿里云香港、新加坡VPS/1核/1G/25G SSD/1T流量/30M带宽/年付¥288【点击购买】