脚本备份交换机配置

来源:互联网 发布:网络病毒软件下载 编辑:程序博客网 时间:2024/05/21 10:26

刚刚学,尝试用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'
原创粉丝点击