def Main(): SupportedOS = ["IOS", "IOS XE", "NX-OS"] # Run session start commands and save session information into a dictionary session = StartSession(crt) # Generate filename used for output files. fullFileName = GetFilename(session, settings, "int_summary") if session['OS'] in SupportedOS: if session['OS'] == "NX-OS": SendCmd = "show interface" # Save raw output to a file. Dumping directly to a var has problems with # large outputs WriteOutput(session, SendCmd, fullFileName) # Create a list that contains all the route entries (minus their line endings) intf_raw = ReadFileToList(fullFileName) # If the settings allow it, delete the temporary file that holds show cmd output if settings['delete_temp']: os.remove(fullFileName + ".txt") summarytable = ParseNXOSIntfStats(intf_raw) field_names = [ "Interface", "Description", "InBPS", "InPPS", "OutBPS", "OutPPS", "InputPackets", "InputErr", "OutputPackets", "OutputErr" ] DictListToCSV(field_names, summarytable, fullFileName) else: SendCmd = "show interfaces" # Save raw output to a file. Dumping directly to a var has problems with # large outputs WriteOutput(session, SendCmd, fullFileName) # Create a list that contains all the route entries (minus their line endings) intf_raw = ReadFileToList(fullFileName) # If the settings allow it, delete the temporary file that holds show cmd output if settings['delete_temp']: os.remove(fullFileName + ".txt") summarytable = ParseIOSIntfStats(intf_raw) field_names = [ "Interface", "Description", "InBPS", "InPPS", "OutBPS", "OutPPS", "InputPackets", "InputErr", "OutputPackets", "OutputErr" ] DictListToCSV(field_names, summarytable, fullFileName) else: error_str = "This script does not support {}.\n" \ "It will currently only run on IOS Devices.".format(session['OS']) crt.Dialog.MessageBox(error_str, "Unsupported Network OS", 16) EndSession(session)
def Main(): ''' The purpose of this program is to capture the MAC Table information from the connected switch excluding the Port-Channels (Uplinks) and ouptut it into a CSV file. ''' SendCmd = 'show mac address- dynamic | exclude Po' # Run session start commands and save session information into a dictionary session = StartSession(crt) # Generate filename used for output files. fullFileName = GetFilename(session, settings, "mac-addresses") # Save raw "show mac address dynamic | exclude Po" output to a file. Dumping directly # to a huge string has problems when the mac table is large (1000+ lines) WriteOutput(session, SendCmd, fullFileName) macs = ReadFileToList(fullFileName) macInfo = ParseMAC(macs) # If the settings allow it, delete the temporary file that holds show cmd output if settings['delete_temp']: os.remove(fullFileName + ".txt") field_names = ['VLAN', 'MAC', 'Interface'] DictListToCSV(field_names, macInfo, fullFileName) # Clean up before exiting EndSession(session)
def Main(): SendCmd = "show vlan brief" show_vlan_widths = (5, 33, 10, -1) # Run session start commands and save session information into a dictionary session = StartSession(crt) # Generate filename used for output files. fullFileName = GetFilename(session, settings, "ActiveVLANs") # Save raw output to a file. Dumping directly to a var has problems with # large outputs WriteOutput(session, SendCmd, fullFileName) # Get a list version of the VLAN table vlan_table = FixedColumnsToList(fullFileName, show_vlan_widths, ext='.txt') # Depending on settings, delete temporary storage of "show vlan" output if settings['delete_temp']: os.remove(fullFileName + ".txt") # Get a table that shows the count of assigned ports, not the names. vlan_summary = PortCountList(vlan_table) # Write data into a CSV file. ListToCSV(vlan_summary, fullFileName) # Clean up before exiting EndSession(session)
def Main(): ''' This purpose of this program is to capture the output of the command entered by the user and save it to a file. This method is much faster than manually setting a log file, or trying to extract only the information needed from the saved log file. ''' SendCmd = crt.Dialog.Prompt("Enter the command to capture") if SendCmd == "": return else: # Save command without spaces to use in output filename. CmdName = SendCmd.replace(" ", "_") # Add a newline to command before sending it to the remote device. SendCmd = SendCmd + "\r\n" # Run session start commands and save session information into a dictionary session = StartSession(crt) # Generate filename used for output files. fullFileName = GetFilename(session, settings, CmdName) # Get the output of our command and save it to the filename specified WriteOutput(session, SendCmd, fullFileName) # Clean up before closing session EndSession(session)
def Main(): # Run session start commands and save session information into a dictionary session = StartSession(crt) # Extract the hostname from the session info. hostname = session['hostname'] save_path = os.path.join(settings['savepath'], hostname) # Get the current date in the format supplied in date_format mydate = GetDateString(settings['date_format']) # Iterate through each command and write a file with the output. for (index, SendCmd) in enumerate(COMMANDS): SendCmd = SendCmd.strip() # Save command without spaces to use in output filename. CmdName = SendCmd.replace(" ", "_") # Add a newline to command before sending it to the remote device. SendCmd = SendCmd + "\n" # Create Filename filebits = [CmdName, hostname, mydate + ".txt"] filename = '-'.join(filebits) # Capture output and write to file (extension already in filename, so # override the default for the function (.txt), or it'll append twice.) fullFileName = GetAbsolutePath(session, save_path, filename) # Write the output of the command to a file. WriteOutput(session, SendCmd, fullFileName, ext="") # If file isn't empty (greater than 3 bytes) # Some of these file only save one CRLF, and so we can't match on 0 bytes if os.path.getsize(fullFileName) > 3: # Open the file we just created. newfile = open(fullFileName, "r") # If the file only contains invalid command error, delete it. for line in newfile: if "% Invalid" in line: newfile.close() os.remove(fullFileName) break else: newfile.close() # If the file is empty, delete it else: os.remove(fullFileName) # Clean up before closing session EndSession(session) crt.Dialog.MessageBox("Device Documentation Script Complete", "Script Complete", 64)
def Main(): SupportedOS = ["IOS", "IOS XE", "NX-OS"] SendCmd = "show ip route" # Run session start commands and save session information into a dictionary session = StartSession(crt) # Get VRF that we are interested in selected_vrf = crt.Dialog.Prompt( "Enter the VRF name.\n(Leave blank for default VRF)") if selected_vrf != "": SendCmd = SendCmd + " vrf {0}".format(selected_vrf) session['hostname'] = session['hostname'] + "-VRF-{0}".format( selected_vrf) # Generate filename used for output files. fullFileName = GetFilename(session, settings, "NextHopSummary") if session['OS'] in SupportedOS: # Save raw "show ip route" output to a file. Dumping directly to a huge # string has problems when the route table is large (1000+ lines) WriteOutput(session, SendCmd, fullFileName) routes = ReadFileToList(fullFileName) if session['OS'] == "NX-OS": routelist = ParseNXOSRoutes(routes) else: routelist = ParseIOSRoutes(routes) # If the settings allow it, delete the temporary file that holds show cmd output if settings['delete_temp']: os.remove(fullFileName + ".txt") # Get a list of all nexthop stats as well as connected networks (2 lists). nexthops, connected, detailed = NextHopSummary(routelist) # Merge the nexthops and connected interfaces into a single list before writing. nexthops.extend(connected) nexthops.extend(detailed) # Write data into a CSV file. ListToCSV(nexthops, fullFileName) else: error_str = "This script does not support {}.\n" \ "It will currently only run on IOS Devices.".format(session['OS']) crt.Dialog.MessageBox(error_str, "Unsupported Network OS", 16) # Clean up before exiting EndSession(session)
def GetInterfaceSamples(ParseIntfStats): for i in range(stat_count): sample_time = datetime.now().strftime("%I:%M:%S") timestamps.append(sample_time) start = time.clock() # Generate filename used for output files. fullFileName = GetFilename(session, settings, "int_summary") # Save raw output to a file. Dumping directly to a var has problems with # large outputs tab.Send('\n') WriteOutput(session, SendCmd, fullFileName) if stat_count != (i + 1): # Print status to the Cisco prompt to keep user aware of progress # This must start with ! to be a Cisco comment, to prevent in-terminal errors warning_msg = "! {0} samples left. DO NOT TYPE IN WINDOW.".format( stat_count - (i + 1)) tab.Send(warning_msg + '\n') tab.WaitForString(session['prompt']) # Read text file into a list of lines (no line endings) intf_raw = ReadFileToList(fullFileName) # If the settings allow it, delete the temporary file that holds show cmd output if settings['delete_temp']: os.remove(fullFileName + ".txt") summarytable = ParseIntfStats(intf_raw) for stat in measurements: for entry in summarytable: if entry['Interface'] in output[stat]: output[stat][ entry['Interface']][sample_time] = entry[stat] else: output[stat][entry['Interface']] = {} output[stat][ entry['Interface']][sample_time] = entry[stat] end = time.clock() if interval - (end - start) > 0: if stat_count != (i + 1): time.sleep(interval - (end - start)) else: crt.Dialog.MessageBox("Did not complete within interval time", "Took Too Long", ICON_STOP) sys.exit(0)
def Main(): ''' This purpose of this program is to capture the output of the "show run" command and save it to a file. This method is much faster than manually setting a log file, or trying to extract the information from a log file. ''' SendCmd = "show run" # Run session start commands and save session information into a dictionary session = StartSession(crt) # Generate filename used for output files. fullFileName = GetFilename(session, settings, "show-run") # Get the output of our command and save it to the filename specified WriteOutput(session, SendCmd, fullFileName) # Clean up before closing session EndSession(session)
def Main(): errorMessages = "" # Get Sessions sessionsArray = GetSessions(my_session_dir, my_site_dir) # Connect to each session and issue a few commands, then disconnect. for my_session in sessionsArray: try: crt.Session.Connect("/S \"" + my_session + "\"") except ScriptError: error = crt.GetLastErrorMessage() # If we successfully connected, we'll do the work we intend to do... # otherwise, we'll skip the work and move on to the next session in # the list. if crt.Session.Connected: crt.Sleep(1000) # Run session start commands and save session information into a dictionary session = StartSession(crt) # Extract the hostname from the session info. hostname = session['hostname'] save_path = os.path.join(settings['savepath'], hostname) # Get the current date in the format supplied in date_format mydate = GetDateString(settings['date_format']) # Iterate through each command and write a file with the output. for (index, SendCmd) in enumerate(COMMANDS): SendCmd = SendCmd.strip() # Save command without spaces to use in output filename. CmdName = SendCmd.replace(" ", "_") # Add a newline to command before sending it to the remote device. SendCmd = SendCmd + "\n" # Create Filename hostip = crt.Session.RemoteAddress filehostip = hostip.replace(".", "_") filehostname = hostname.replace("/", "-") filehostname = hostname.replace("\\", "-") filebits = [filehostname, filehostip, CmdName, mydate + ".txt"] filename = '-'.join(filebits) # Capture output and write to file (extension already in filename, so # override the default for the function (.txt), or it'll append twice.) fullFileName = GetAbsolutePath(session, save_path, filename) # Write the output of the command to a file. WriteOutput(session, SendCmd, fullFileName, ext="") # If file isn't empty (greater than 3 bytes) # Some of these file only save one CRLF, and so we can't match on 0 bytes if os.path.getsize(fullFileName) > 3: # Open the file we just created. newfile = open(fullFileName, "r") # If the file only contains invalid command error, delete it. for line in newfile: if "% Invalid" in line: newfile.close() os.remove(fullFileName) break else: newfile.close() # If the file is empty, delete it else: os.remove(fullFileName) # Clean up before closing session EndSession(session) # Now disconnect from the remote machine... crt.Session.Disconnect() # Wait for the connection to close while crt.Session.Connected == True: crt.Sleep(100) crt.Sleep(1000) else: errorMessages = errorMessages + "\n" + "*** Error connecting to " + my_session + ": " + error if errorMessages == "": crt.Dialog.MessageBox("No Errors were detected.") else: crt.Dialog.MessageBox("The following errors occurred:\n" + errorMessages)