def run_commands(a_device): """ Function using Netmiko to connect to each of the devices. Execute commands on each device from commands.txt """ # Network device definition for Netmiko ios_device = { 'device_type': 'cisco_ios', 'ip': a_device, 'username': username, 'password': password, } # Connect to device, run commands, output to file try: current_time = datetime.now().strftime("%y_%m_%d_%H%M") print ('Connecting to device ' + a_device) remote_conn = ConnectHandler(**ios_device) # Grab the hostname of the device, so it can be used as a filename hostname = remote_conn.send_command("show run | i hostname") hostname = hostname[9:] #open file to write command output file = open(hostname + " - " + a_device + " " + current_time + '.txt', 'w') # Print output to console screen print('-------------- Running script on ' + a_device + ' - ' + hostname + ' ------------------') file.write('======== ' + a_device + ' @ ' + hostname + ' ========') file.write("\n") # run and output the commands in commands.txt output=remote_conn.send_config_set(commands_list) file.write(output) # Close the file file.close() # Cleanly disconnect SSH session remote_conn.disconnect() except (AuthenticationException): print ('Authentication Failure: ' + a_device) Authfailure.write('\n' + a_device) except (NetMikoTimeoutException): print ('\n' + 'Timeout to device: ' + a_device) Timeouts.write('\n' + a_device) except (SSHException): print ('SSH might not be enabled: ' + a_device) SSHException.write('\n' + a_device) except (EOFError): print ('\n' + 'End of attempting device: ' + a_device) EOFError.write('\n' + a_device) except unknown_error: print ('Some other error: ' + str(unknown_error))
outF.write("################\n") outF.write("################\n") print(host + " Completed") operationLOG = open("OperationLog.txt", "a") operationLOG.write("Switch " + host + " Completed \n") device.send_command("write memory\n") time.sleep(2) device.disconnect() else: print("NOTHING WAS DONE to host" + host) except (AuthenticationException): print('Authentication Failure: ' + host) Authfailure.write('\n' + host) continue except (NetMikoTimeoutException): print('\n' + 'Timeout to device: ' + host) Timeouts.write('\n' + host) continue except (SSHException): print('SSH might not be enabled: ' + host) SSHException.write('\n' + host) continue except (EOFError): print('\n' + 'End of attempting device: ' + host) EOFError.write('\n' + host) continue except unknown_error: print('Some other error: ' + str(unknown_error)) print(f'Processed {line_count} lines.') except: print("\nBroken")