A Python Script to Backup Cisco Routers and Switches
| March 20th, 2017Backup Cisco Routers and Switches
#!/usr/bin/python import pexpect,sys,string,os,time,subprocess,getpass if len(sys.argv) !=2: print ("usage: backup [user@]hostname") else: input_data = sys.argv[1] data=input_data.split("@") switch_un = data[0] switch_ip = data[1] switch_pw1 = getpass.getpass("Enable Password:") switch_pw2 = getpass.getpass("Privilege Password:") basic_backup_directory = "/tmp/Network_Backups" print ("Please wait ...") try: try: child = pexpect.spawn('ssh %s@%s' % (switch_un, switch_ip)) child.timeout = 10 child.expect('assword:') child.sendline(switch_pw1) except pexpect.TIMEOUT: raise OurException("Couldn't log on to the switch") child.sendline('disable') child.expect('>') child.sendline('terminal length 0') child.expect('>') child.sendline('enable') child.expect('Password:') child.sendline(switch_pw2) child.expect('#') network_hostname = child.before #network_hosname contains some strange characters that should be removed j=0 network_hostname_2="" for i in range(len(network_hostname)): if ord(network_hostname[i]) > 32: network_hostname_2+=network_hostname[i] child.sendline('show run') child.expect(network_hostname_2+"#") data= child.before except (pexpect.EOF,pexpect.TIMEOUT), e: error("Error while trying to login.") raise this_date=time.strftime("%d%m%Y") this_moment=time.strftime("%X") full_backup_directory= basic_backup_directory+"/"+network_hostname_2 #creating a directory and then opening/creating/writing into a file in the specified directory. if not os.path.exists(full_backup_directory): os.makedirs(full_backup_directory) file_name= network_hostname_2+"_"+this_date+".txt" with open (os.path.join(full_backup_directory,file_name),'wb') as temp_file: temp_file.write(data) output= subprocess.check_output(["rsync","-rvzhe","ssh",full_backup_directory,"root@192.168.XX.XX:/mnt/STORAGE_01/backups/Switches"]) print output