Import timefrom Netmiko import connecthandlerfrom netmiko.ssh_exception import Netmikotimeoutexceptionfrom netmiko.ssh _exception Import netmikoauthenticationexceptionimport sysimport getpassfrom datetime import Datetimeimport osdef Networkdevice (USERNAME,PASSWORD,IPLIST,ENABLEPASS): RT = {' Device_type ': ' Cisco_ios ', ' username ': username, ' password ' ':p assword, ' IP ': iplist, ' secret ': Enablepass} print ('-' * ') Print (U ' [+] connecting to network device {0} ... '. Format (IP list)) Net_connect = Connecthandler (**rt) net_connect.enable () hostname = Net_connect.find_prompt (). Replace ("#", "" ") Print (U ' [+] hostname:{0} '. Format (hostname)) Timestr = Time.strftime ('%y-%m-%d-%h-%m-%s ', Time.localtime (Time.time () ) cmd = ' show running ' filename = (U ' {0}_{1}_{2}.txt '. Format (IPLIST,CMD,TIMESTR)) filepath = R ' c:\netpy\5pyresult\/' if O S.path.exists (filepath): message = ' ok,the '%s ' dir exists. ' Else:message = ' Now, I'll create the '%s ' Os.makedirs (filep ATH) Save = open (filepath + filename, ' W ') Print (U ' [+]Executing {0} command '. Format (cmd)) output = Net_connect.send_command (cmd) time.sleep (2) save.write (output) print (U ' [+ ] {0} command Executed,result is saved at {1}! '. Format (cmd,filename)) Save.close () Net_connect.disconnect () if __name__ = = ' __main__ ': print "[+] the program is running. ... "username = raw_input (' username: ') password = getpass.getpass () Enablepass = Raw_input (' Enable: ') Filepath2 = R ' c:\n Etpy\\ ' if Os.path.exists (filepath2): message = ' ok,the '%s ' file exists. ' Else:message = ' Now, I'll create the '%s ' OS. Makedirs (filepath2) for IPs in Open (R ' C:\netpy\iplist.txt ', ' R '): Start_time = DateTime.Now () IPList = Ips.replace (' \ n ', ' ') Try:networkdevice (username,password,iplist,enablepass) except (Eoferror, netmikotimeoutexception): print (' Can not Connect to Device ') except (Eoferror, netmikoauthenticationexception): Print (' Username/password wrong! ') except ( Valueerror,netmikoauthenticationexception): Print (' Enable password wrong! ') print "time elapsed: {0}\n". Format (DATetime.now ()-Start_time) Time.sleep (2)
79837161
Python Netmiko for Cisco network device Configuration Backup