作為一名網工,有時候面對着大量的網絡設備,設備備份工作是件很麻煩的事情。
以下是本人親測成功的腳本代碼,一鍵進行設備備份
腳本如下:
# -*- coding: gbk -*- # 制作人:Tim # 日期:2020-1-2 import telnetlib import time import re import getpass username = input('請輸入你的賬號:') passwd = getpass.getpass('請輸入你的賬號密碼:') commands = ['term len 0', 'show run', 'show mac add','show cdp nei'] timestr1 = time.strftime('%Y-%m-%d %X', time.localtime()) timestr = time.strftime('%Y-%m-%d', time.localtime()) def main(host): tn = telnetlib.Telnet(host, port=23, timeout=3) time.sleep(2) #tn.set_debuglevel(2) tn.read_until(b"Username:", timeout=3) tn.write(username.encode('ascii') + b'\n') tn.read_until(b"Password:") tn.write(passwd.encode('ascii') + b'\n') print('己成功登錄%s [%s]' % (host, timestr1)) time.sleep(0.5) tn.read_until(b"#") hostname_command = 'show run | in hostname' tn.write(hostname_command.encode('ascii') + b'\n') time.sleep(1) cmd_text = tn.read_very_eager().decode('ascii') match = re.split(' ', cmd_text) match1 = match[-1].replace('\n', ' ').replace('\r', '').replace('#', '') hostlist = re.split(' ', match1) hostname = hostlist[1] print(hostname) command_result = tn.read_very_eager().decode('ascii') filepath = 'D:\\SWbackup\\log\\' filename = ('%s %s %s' % (host, hostname, timestr)) print(filename) save = open(filepath + filename + '.txt', 'a', newline='') # 以寫的方式來打開文件 print(command_result, file=save) tn.close() def do_work(host_list, all_num): num = 0 for host in host_list: try: main(host) num += 1 print("\r備份進度為:%.2f %%" % (num * 100 / all_num), end="") print('') print("-" * 50) except: f2 = open(r'D:\SWbackup\error.txt', 'a+') print('Can not connect to Device') print('%s is error' % host, file=f2) print('*' * 20 + '%s' % timestr1 + '*' * 20, file=f2) num += 1 print("\r備份進度為:%.2f %%" % (num * 100 / all_num), end="") print('') print("-" * 50) f2.close() host_list = [] f1 = open(r'D:\SWbackup\sw_telnet.txt', 'r') # 獲取文件中的每行IP for line in f1.readlines(): line = line.replace('\n', '') host_list.append(line) f1.close print(host_list) all_num = len(host_list) do_work(host_list, all_num)
sw_telnet寫上需要備份的設備IP
哪台設備備份失敗記錄下來
自動生成的備份文件
PS:本人非專業的程序員,如寫得不好請多擔待,也歡迎留言評論,謝謝