Chinaunix首页 | 论坛 | 博客
  • 博客访问: 11712
  • 博文数量: 4
  • 博客积分: 15
  • 博客等级: 民兵
  • 技术积分: 15
  • 用 户 组: 普通用户
  • 注册时间: 2010-10-26 11:53
文章分类
文章存档

2019年(1)

2017年(1)

2014年(1)

2013年(1)

我的朋友

分类: 系统运维

2017-09-05 11:04:53


原来用expect写了一个备份交换机配置的脚本,但经常是出错或者是备份不成功
现在用python重写过,测试了下,三十多台交换机,总共备份时间也就一秒多,也比原来的脚本稳定多了

再另外说明下:
sw.txt文件中就是需要备份的交换机的IP,每行一个IP就行了
另外需要自己建立一个tftp服务器,交换机配置是备份到tftp服务器上,然后再对配置文件打包等动作

点击(此处)折叠或打开

  1. #!/usr/bin/env python
  2. #coding:utf-8

  3. import sys
  4. import os
  5. import telnetlib
  6. import time
  7. import threading
  8. import datetime

  9. #Use for loop to telnet into each routers and execute commands
  10. class Bakconf(threading.Thread):
  11.     def __init__(self,host,upwd,epwd):
  12.         threading.Thread.__init__(self)
  13.         self.host=host
  14.         self.upwd=upwd
  15.         self.epwd=epwd

  16.     def run(self):
  17.         try:
  18.             tn = telnetlib.Telnet(self.host,port=23,timeout=5)
  19.         except:
  20.             print "Can't connection %s"%self.host
  21.             return
  22.         tn.set_debuglevel(5)
  23.         tn.write(self.upwd +b"\n")
  24.         tn.write("en\n")
  25.         tn.write(self.epwd + b"\n")
  26.         tn.write("copy startup-config tftp:\n")
  27.         tn.write(tftpser + b"\n")
  28.         tn.write(b"\n")
  29.         time.sleep(1)
  30.         tn.write("exit\n")
  31.         tn.close()

  32. def main():
  33.     #user_exec_mode_password
  34.     upwd1 = "**********"
  35.     upwd2 = "**********"
  36.     #privilege_exec_mode_password
  37.     epwd1 = "**********"
  38.     epwd2 = "**********"
  39.     global tftpser
  40.     tftpser="192.168.103.71"

  41.     for host in open(r'/backup/shell/sw.txt').readlines():
  42.         dsthost = host.strip('\n')
  43.         bakconf=Bakconf(dsthost, upwd1, epwd1)
  44.         bakconf.start()

  45.     hostlist2=["10.1.11.237","10.1.11.238","192.168.103.239"]
  46.     for host in hostlist2:
  47.         bakconf=Bakconf(host, upwd2, epwd2)
  48.         bakconf.start()

  49.     #Backup switch config and tar
  50.     time.sleep(1)
  51.     dtime=datetime.datetime.now().strftime("%Y%m%d%H%M%S")
  52.     os.popen('tar -cjf /backup/cisco/switch-'+dtime+'.tar.bz2 '+ '/tftproot')
  53.     os.popen('rm -fr /tftproot/*')
  54.     os.popen('find /backup/cisco/ -mtime +90 -exec rm {} \;')

  55. if __name__=="__main__":
  56.     main()

阅读(536) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~