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("user\n");//telnet用户名
echo $telnet->read_till("password: ");
$telnet->write("passwd\n");//telnet密码
echo $telnet->read_till(">");
//echo $telnet->read_till(":> ");
$telnet->write("dis dev\n");//执行命令1
echo $telnet->read_till(">");
$telnet->write("dis dev\n");//执行命令2
echo $telnet->read_till(">");
// TODO

echo $telnet->close();//关闭连接
链接到文章: https://jiloc.com/45742.html

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注