Python3 封装简化 telnetlib 包为 TelnetLib

telnetLib.py

#!/usr/bin/env python3
# -*- coding: UTF-8 -*-

import time
import telnetlib

# from functools import wraps


# def run_time(f):
#     @wraps(f)
#     def core(*args, **kwargs):
#         start_time = time.time()
#         f(*args, **kwargs)
#         end_time = time.time()
#         msecs_time = (end_time - start_time) * 1000
#         print("程序运行时间:%s 毫秒" % msecs_time)
#     return core


class TelnetLib(object):

    def __init__(self):

        self.tn = None
        self._output = False
        self._system = False
        self.sleep = None
        self.timeout = None
        self.data = []

        self.EXIT = b'quit\n'
        self.USERNAME = b'Username:' or b'Login:' or b'username:' or b'login:'
        self.PASSWORD = b'Password:' or b'password:'

    @staticmethod
    def format(data):
        return data.encode('UTF-8') + b'\n'

    # @run_time
    def link(self, host, port=23, sleep=1, timeout=3):
        try:
            self.sleep = sleep
            self.timeout = timeout
            self.tn = telnetlib.Telnet(host, port, self.timeout)
        except Exception as e:
            raise ValueError('设备连接错误:%s' % e)

    # @run_time
    def login(self, username, password):
        try:
            time.sleep(self.sleep)
            self.data.append(self.tn.read_until(self.USERNAME, self.timeout))
            self.tn.write(self.format(username))
            time.sleep(self.sleep)
            self.data.append(self.tn.read_until(self.PASSWORD, self.timeout))
            self.tn.write(self.format(password))
            time.sleep(self.sleep)
            if self._output is True:
                self.tn.write(self.format('screen-length disable'))
        except Exception as e:
            raise ValueError('设备登录错误:%s' % e)

    # @run_time
    def system(self):
        self._system = True
        self.tn.write(self.format('system-view'))
        time.sleep(self.sleep)

    # @run_time
    def shell(self, command):
        try:
            self.tn.write(self.format(command))
            time.sleep(self.sleep)
            self.data.append(self.tn.read_very_eager())
        except Exception as e:
            raise ValueError('命令执行错误:%s' % e)

    def log(self):
        return ''.join([data.decode('UTF-8') for data in self.data if data])

    def exit(self):
        try:
            if self._system is True:
                self.tn.write(self.EXIT)
            self.tn.write(self.EXIT)
            time.sleep(self.sleep)
            self.data.append(self.tn.read_very_eager())
            self.tn.close()
        except Exception as e:
            raise ValueError('设备退出错误:%s' % e)


if __name__ == '__main__':
    telnet = TelnetLib()
    telnet.link(host='xxx.xxx.xxx.xxx')
    telnet.login(username='xxx', password='xxx')
    telnet.shell(command='display clock')
    telnet.exit()
    log = telnet.log()
    print(log)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值