- #!/usr/bin/env python
- #coding:utf-8
- import sys
- import os
- import telnetlib
- import time
- import threading
- import datetime
- #Use for loop to telnet into each routers and execute commands
- class Bakconf(threading.Thread):
- def __init__(self,host,upwd,epwd):
- threading.Thread.__init__(self)
- self.host=host
- self.upwd=upwd
- self.epwd=epwd
- def run(self):
- try:
- tn = telnetlib.Telnet(self.host,port=23,timeout=5)
- except:
- print "Can't connection %s"%self.host
- return
- tn.set_debuglevel(5)
- tn.write(self.upwd +b"\\n")
- tn.write("en\\n")
- tn.write(self.epwd + b"\\n")
- tn.write("copy startup-config tftp:\\n")
- tn.write(tftpser + b"\\n")
- tn.write(b"\\n")
- time.sleep(1)
- tn.write("exit\\n")
- tn.close()
- def main():
- #user_exec_mode_password
- upwd1 = "**********"
- upwd2 = "**********"
- #privilege_exec_mode_password
- epwd1 = "**********"
- epwd2 = "**********"
- global tftpser
- tftpser="192.168.103.71"
- for host in open(r'/backup/shell/sw.txt').readlines():
- dsthost = host.strip('\\n')
- bakconf=Bakconf(dsthost, upwd1, epwd1)
- bakconf.start()
- hostlist2=["10.1.11.237","10.1.11.238","192.168.103.239"]
- for host in hostlist2:
- bakconf=Bakconf(host, upwd2, epwd2)
- bakconf.start()
- #Backup switch config and tar
- time.sleep(1)
- dtime=datetime.datetime.now().strftime("%Y%m%d%H%M%S")
- os.popen('tar -cjf /backup/cisco/switch-'+dtime+'.tar.bz2 '+ '/tftproot')
- os.popen('rm -fr /tftproot/*')
- os.popen('find /backup/cisco/ -mtime +90 -exec rm {} \\;')
- if __name__=="__main__":
- main()
- #该片段来自于http://www.codesnippet.cn/detail/061120136941.html
来源: http://www.codesnippet.cn/detail/061120136941.html