Ejemplo n.º 1
0
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)
Ejemplo n.º 2
0
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)
Ejemplo n.º 3
0
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)
Ejemplo n.º 4
0
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)
Ejemplo n.º 5
0
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)
Ejemplo n.º 6
0
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)
Ejemplo n.º 7
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)
Ejemplo n.º 8
0
def Main():
    '''
    The purpose of this program is to capture the CDP information from the connected
    switch and ouptut it into a CSV file.
    '''
    SendCmd = "show cdp neighbors detail"

    # Run session start commands and save session information into a dictionary
    session = StartSession(crt)

    # Generate filename used for output files.
    fullFileName = GetFilename(session, settings, "cdp")

    raw = CaptureOutput(session, SendCmd)

    cdpInfo = ParseCDP(raw)
    field_names = [
        'Local Intf', 'Remote ID', 'Remote Intf', 'IP Address', 'Platform'
    ]
    DictListToCSV(field_names, cdpInfo, fullFileName)

    # Clean up before exiting
    EndSession(session)
Ejemplo n.º 9
0
def main():
    # Get configfile to load
    configfile = get_configfile()

    # See if we got our input file
    if configfile != "":
        #Do we continue on errors or not?
        result = crt.Dialog.MessageBox(
            "Stop on Errors?", "Error",
            ICON_QUESTION | BUTTON_YESNO | DEFBUTTON2)
        if result == IDYES:
            error_stop = True
        else:
            error_stop = False

        # Run session start commands and save session information into a dictionary
        session = StartSession(crt)

        # Get CRT Tab for sending commands
        tab = session['tab']

        # Define the line endings we are going to look for while entering commands
        endings = ["\r\n", ")#"]

        # Get the current date in the format supplied in date_format
        my_date = GetDateString(settings['date_format'])

        # Define variable to be used to identify if we are sending banner config lines and end mark
        banner_lines = False
        end_of_banner = ""

        # Define my_line_count variable to tell where we found an error, if we do.
        my_line_count = 0

        # Break out the input file path and name minus the extension so we can create output filename
        c_filename, c_extension = os.path.splitext(configfile)

        # Create Filename
        file_bits = [c_filename, "Config_Load", my_date + c_extension]
        output_file = '-'.join(file_bits)

        # Open the output file for writing
        out_file = open(output_file, 'w')

        # Write header to output file
        out_file.write('Output of all Configuration Commands\r\n')
        out_file.write('Error Lines will start with *** Invalid Command :\r\n')
        out_file.write('\r\n========\r\n')

        # Enter configuration mode
        tab.Send("config term\n")

        # Loop through each line of the input config file.
        with open(configfile, "rU") as InputFile:
            for line in InputFile:
                try:
                    # Increment line count
                    my_line_count += 1
                    # Strip line endings so as not to get double spacing
                    line = line.strip()
                    # Send line to device
                    tab.Send(line + "\n")
                    # Check to see if it was a banner line as we won't get the prompt back
                    if "banner" in line:
                        banner_lines = True
                        # Determine what the end of banner character is going to be
                        end_of_banner = line[-1]
                    # If we're still processing banner lines continue
                    elif banner_lines:
                        # Check if end of Banner
                        if line == end_of_banner:
                            banner_lines = False
                        # Wait for echo of banner line
                        tab.WaitForString(line.strip())
                    else:
                        # Wait for echo of config command
                        tab.WaitForString(line.strip())

                    # Loop to capture every line of output.  If we get CR/LF (first entry
                    # in our "endings" list), then write that line to the file.  If we get
                    # our prompt back (which won't have CR/LF), break the loop b/c we found the
                    # end of the output.
                    while True:
                        next_line = tab.ReadString(endings)
                        # If the match was the 1st index in the endings list -> \r\n
                        if tab.MatchIndex == 1:
                            # Strip newlines from front and back of line.
                            next_line = next_line.strip('\r\n')
                            # If there is something left, check for Invalid command.
                            if "% Invalid" in next_line:
                                # Strip line endings from line.  Also re-encode line as ASCII
                                # and ignore the character if it can't be done (rare error on
                                # Nexus)
                                out_file.write('*** Invalid Command : ' +
                                               line.strip('\r\n').encode(
                                                   'ascii', 'ignore') + '\r\n')
                                # If we're stopping on errors, raise an exception so we'll stop on next iteration
                                if error_stop:
                                    raise NameError('InvalidCommand')
                                break
                            elif banner_lines:
                                # write out banner lines as a special case
                                out_file.write(
                                    line.strip('\r\n').encode(
                                        'ascii', 'ignore') + '\r\n')
                                break
                        else:
                            # We got our prompt (MatchIndex is 2), so break the loop
                            out_file.write(
                                line.strip('\r\n').encode('ascii', 'ignore') +
                                '\r\n')
                            break
                # If we've raised an exception for an Invalid command and are supposed to stop
                # present a dialog box with a message indicating which line had the invalid command.
                except NameError:
                    crt.Dialog.MessageBox(
                        "Invalid Command Found\n On line: " +
                        str(my_line_count), "Error", 16)
                    break

        # End configuration mode
        tab.Send("end\n")

        # Close input and output files
        out_file.close()
        InputFile.close()
        # Clean up before closing session
        EndSession(session)

        # Show dialog with completion message
        crt.Dialog.MessageBox("Config Load Complete", "Script Complete", 64)

    else:
        crt.Dialog.MessageBox("No Configfile Provided", "Error", 16)
Ejemplo n.º 10
0
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)
Ejemplo n.º 11
0
def Main():
    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)

    SupportedOS = ["IOS", "IOS XE", "NX-OS"]

    # Run session start commands and save session information into a dictionary
    session = StartSession(crt)
    SendCmd = "show interface"
    tab = session['tab']

    output = {}
    for name in measurements:
        output[name] = {}

    timestamps = []

    if session['OS'] in SupportedOS:
        if session['OS'] == "NX-OS":
            GetInterfaceSamples(ParseNXOSIntfStats)
        else:
            GetInterfaceSamples(ParseIOSIntfStats)
    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)

    field_names = ["Interface"]
    field_names.extend(timestamps)

    fullFileName = GetFilename(session, settings, "graph")

    for stat in measurements:
        temp_csv_list = []
        header = [[stat]]
        empty_line = [[]]
        for key in sorted(output[stat].keys(), key=alphanum_key):
            temp_dict = {"Interface": key}
            temp_dict.update(output[stat][key])
            temp_csv_list.append(temp_dict)
        ListToCSV(header, fullFileName, mode='ab')
        DictListToCSV(field_names, temp_csv_list, fullFileName, mode='ab')
        # Add seperator line
        ListToCSV(empty_line, fullFileName, mode='ab')

    EndSession(session)
    crt.Dialog.MessageBox("Interface Statistic Gathering Complete",
                          "Script Complete", 64)