1. 程式人生 > >指令碼備份交換機配置

指令碼備份交換機配置

剛剛學,嘗試用python來備份交換機裝置配置

該配置參考了http://bbs.chinaunix.net/thread-1710118-1-1.html

#!/usr/bin/python

import sys
import time
import os
import pexpect#使用pexpect模組來做遠端控制
now = time.strftime("%y%m%d", time.localtime())
if not os.path.exists(r"/root/backup/%s" %now): #做個判斷,如果該資料夾存在就不重複建立賦許可權
    os.mkdir(r"/root/backup/%s" %now)#以現在時間為名新建資料夾
    os.chmod(r"/root/backup/%s" %now ,0777) #賦予許可權
aa = open (r'%s/log.txt' %now, "w") 
execlog 
= open (r'/root/backup/%s/pexpectlog.txt' %now, "w")
IP_PASS = open(r'/root/backup/%s/IPLIST.txt' %now ,'r')#將IP地址以及賬號密碼用逗號隔開,每個交換機一行
while True:
READALL = IP_PASS.readline()
if not READALL:#當地址讀取完則退出迴圈
   print 'END'
   break
ALLLIST = READALL.split(',')
READIP = ALLLIST[0]
READUSE = ALLLIST[1]
READPASS = ALLLIST[2]
READEN = ALLLIST[3]
IPSP = READIP.split()
IPADD = IPSP[0]
PATH = now + "test"
foo = pexpect.spawn('/usr/bin/telnet %s' % READIP,logfile=execlog)#發起遠端連線並記錄執行過程
login = foo.expect(['Username:','Connection refused'])#之後就是一系列的檢測關鍵字並輸入配置的過程
if login == 0:
   foo.sendline(READUSE)
   foo.expect(['Password:'])
   foo.sendline(READPASS)
elif login == 1:
   print "%s connection refused!!!"
   break
configmode = foo.expect(['>','#'])
if configmode == 0 :
   foo.sendline('en')
   foo.expect(['Password:'])
   foo.sendline(READEN)
   foo.expect(['#'])
   foo.sendline('copy running-config tftp:')
   elif configmode == 1 :
            foo.sendline('copy running-config tftp:')
foo.expect(['Address or name of remote host'])
foo.sendline('192.168.1.1')
foo.expect(['Destination filename'])
foo.sendline(now + IPADD)
a = foo.expect (['!!','Error',pexpect.EOF,pexpect.TIMEOUT])
if a == 0:
   aa.write('%s.....ok\n'%IPADD)
   print "%s......ok\n" %IPADD
   foo.expect(['#'])
   foo.sendline('quit')
elif a == 1 or 2 or 3:
   aa.write('%s......failed\n'%IPADD)
   print "%s......failed\n" %IPADD
   foo.sendline('quit')
foo.interact
print 'ALL DONE'