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)