Python 实现telnet客户端代码

Python telnet 编程

Python自带 telnetlib 模块,可以用于编写telnet**客户端**连接,遵循**RFC 854: TELNET Protocol Specification** 协议。python 中定义了telnet 格式,可以未交互式telnet客户端,也可以采用发送命令,并获取命令执行结果的方式。
采用交互式方式调用,直接采用interact 方法即可,在采用非交互方式,建议采用read_until 确定信令执行。具体实现间如下代码。


class telnetclass(object):
    
    def __init__(self):
        self.tc = telnetlib.Telnet()
        self.tc.set_debuglevel(10)
    
    def log_in(self,ip=None,type=None):
        # logging.info("正在连接epack")
        self.tc.open(ip,23)
        # time.sleep(4)
        self.tc.read_until(b'login: ',timeout=10)
        self.tc.write("root".encode('ascii') + b'
')
        self.tc.read_until(b"hytera",timeout=120)
        logging.info("%s 登录成功"%ip)

        # result = print(self.tc.read_all().decode('ascii'))
        # return result
        # # time.sleep(4)

    
    def execute_command(self,cmd,lag=''):
        """
        cmd 表示要执行的命令
        lag:命令执行后应该具有的信息,用于表示命令执行成功

        """
        # self.tc.read_until(b'# ',timeout=60)
        logging.info("执行命令{} ".format(cmd))
        self.tc.write(cmd.encode('ascii')+b'
')
        # time.sleep(90)
        cmd_result = self.tc.read_eager().decode("ascii")
        self.tc.read_until(lag.encode('ascii'))
        logging.info("{}执行结果为 {}".format(cmd,cmd_result))
        # logging.info("{}执行完成".format(cmd))
        return cmd_result
    
    def execute_command_wait(self,cmd,fp,wait_time=900):
        """
        用于执行命令 等待命令执行时间,将结果写入文件内
        """
        logging.info("执行命令{} ".format(cmd))
        self.tc.write(cmd.encode('ascii')+b'
')
        time.sleep(int(wait_time))
        cmd_result = self.tc.read_very_eager().decode("ascii")
        time_stamp = time.asctime()
        fp.write(time_stamp)
        fp.write("
")
        fp.write(cmd_result)
        logging.info("{}执行结果为 {}".format(cmd,cmd_result))
        # logging.info("{}执行完成".format(cmd))
        # return cmd_result



    # 退出telnet
    def logout_host(self):
        self.tc.write(b"exit
")
原文地址:https://www.cnblogs.com/Finding-bugs/p/14172646.html