zoukankan      html  css  js  c++  java
  • 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
    ")
    
  • 相关阅读:
    css3 可穿透的盒子标签属性 pointer-events
    Visual Basic 6.0精简版下载地址
    VB实现七彩过渡渐变色效果
    ExcelVBA联考中学校自动分配
    VB经典的推箱子小游戏源程序
    坦克大战小游戏源程序
    扫雷初级版V1.0源程序
    班级随机点名程序
    VB弹力球源程序
    老师如何听课和评课?4个维度、20个观察视角、68个观察点!
  • 原文地址:https://www.cnblogs.com/Finding-bugs/p/14172646.html
Copyright © 2011-2022 走看看