#!/usr/bin/env python
#coding:utf-8
import telnetlib
import re
import codecs
import time
import datetime
import os
#獲取當(dāng)前時間
now = datetime.datetime.now()
#設(shè)置輸出路徑及時間戳格式
path = "./conf/%s"%now.strftime('%Y%m%d')
#創(chuàng)建目錄
if not os.path.exists(path):
? ? os.makedirs(path)
#讀取交換機信息
contents = open(r'./switches.txt').readlines()
for content in contents:
? ? try:
? ? ? ? host = content.split(' ')[0]
? ? ? ? # user = content.split(' ')[1]
? ? ? ? # passwd = content.split(' ')[2]
? ? ? ? #建立telnet連接
? ? ? ? tn = telnetlib.Telnet(host, timeout=15)
? ? ? ? #tn.set_debuglevel(5)
? ? ? ? time.sleep(3)
? ? ? ? # tn.write(user.encode('ascii') +b'\n')
? ? ? ? tn.write(b'admin\n')
? ? ? ? time.sleep(1)
? ? ? ? # tn.write(passwd.encode('ascii'))
? ? ? ? tn.write(b'Admin@huawei.com\n')
? ? ? ? time.sleep(1)
? ? ? ? #執(zhí)行命令
? ? ? ? tn.write(b'sys\n')
? ? ? ? tn.write(b'user-interface vty 0 4\n')
? ? ? ? tn.write(b'screen-length 0\n')
? ? ? ? tn.write(b'quit\n')
? ? ? ? tn.write(b'quit\n')
? ? ? ? time.sleep(3)
? ? ? ? tn.write(b'dis cur\n')
? ? ? ? tn.write(b'quit\n')
? ? ? ? #獲取輸出內(nèi)容到文件
? ? ? ? output = tn.read_all()
? ? ? ? f = open('%s/%s'%(path,host+'.cfg'),'wb')
? ? ? ? f.write(output)
? ? ? ? #結(jié)束
? ? ? ? f.close()
? ? ? ? tn.close()
? ? ? ? #輸出日志
? ? ? ? print (str(now.strftime('%Y-%m-%d %H:%M:%S ')+host+' Success'))
? ? except:
? ? ? ? print (str(now.strftime('%Y-%m-%d %H:%M:%S ')+host+' Failed'))
說明:
該腳本實現(xiàn)自動批量備份,通過讀取腳本根目錄中 switches.txt 文本里的IP信息。進行備份后保存在腳本根目錄中的conf目錄下的以當(dāng)前日期下的IP文件名。如下圖

switches.txt
192.168.13.249?
192.168.1.254?