# !/usr//bin/python3 # -*- coding:UTF-8 -*- from telnetlib import Telnet import time, os, datetime, json import logging class TelnetClient(): def __init__(self): self.tn = Telnet() def __login_host(self, ip, username, password, enable=None, verbose=True): try: self.tn.open(ip, port=23) except: logging.warning('%s网络连接失败' % ip) return False self.tn.read_until(b'Username:', timeout=1) self.tn.write(b'\n') self.tn.write(username.encode() + b'\n') rely = self.tn.expect([], timeout=1)[2].decode().strip() # 读显 if verbose: print(rely) self.tn.read_until(b'Password:', timeout=1) self.tn.write(password.encode() + b'\n') rely = self.tn.expect([], timeout=1)[2].decode().strip() if verbose: print(rely) if enable is not None: self.tn.write(b'enable\n') self.tn.write(enable.encode() + b'\n') if verbose: rely = self.tn.expect([], timeout=1)[2].decode().strip() print(rely) time.sleep(1) time.sleep(2) rely = self.tn.read_very_eager().decode() if 'Login invalid' not in rely: logging.warning('%s登陆成功' % ip) return True else: logging.warning('%s登陆失败,用户名或密码错误' % ip) return False def __do_cmd(self, cmd, location=None): if location: os.system('mkdir backup\\{}'.format(location)) with open('backup/{}/configuration_{}.txt'.format(location, datetime.date.today()), 'w') as f: self.tn.write(cmd.encode().strip() + b'\n') time.sleep(3) rescmd = self.tn.read_very_eager().decode() f.write(rescmd) logging.warning('命令执行结果:\n %s' % rescmd) return True else: os.system('mkdir backup') with open('backup/configuration_{}.txt'.format(location, datetime.date.today()), 'w') as f: self.tn.write(cmd.encode().strip() + b'\n') time.sleep(3) rescmd = self.tn.read_very_eager().decode() f.write(rescmd) logging.warning('命令执行结果:\n %s' % rescmd) return True def telnet_login(self, ip, user, pwd, enable=None, cmd=None, location=None): res1 = self.__login_host(ip, user, pwd, enable) if res1: for i in cmd.split(';'): self.__do_cmd(i, location) self.__logout_host() return True else: self.__logout_host() return False def __logout_host(self): self.tn.close() if __name__ == '__main__': username = 'cisco' # 用户名 password = 'cisco' # 密码 # 存放设备登陆信息和要执行的命令(多条命令用;隔开),示例:["ip", "username", "password", "enable_password", "terminal length 0;show run", "backup_path"] lists = 'list.text' with open('test.txt', 'rt', encoding='utf-8') as list_obj: # textline = list_obj.readline() # while textline != '': # print(json.loads(textline)) # textline = list_obj.readline() telnet_client = TelnetClient() for line in list_obj: hostmsg = json.loads(line) telnet_client.telnet_login(hostmsg[0], hostmsg[1], hostmsg[2], hostmsg[3], hostmsg[4])