def get_auth_list(session, to_cvs=False): """ A function that captures the WLC AireOS auth-list and returns an output list :param session: The script object that represents this script being executed :type session: session.Session :return: A list of MAC auth-list :rtype: list of lists """ send_cmd = "show auth-list" output_raw = session.get_command_output(send_cmd) # TextFSM template for parsing "show auth-list" output template_file = session.script.get_template( "cisco_aireos_show_auth_list.template") output = utilities.textfsm_parse_to_list(output_raw, template_file, add_header=True) if to_cvs: output_filename = session.create_output_filename("auth-list", ext=".csv") utilities.list_of_lists_to_csv(output, output_filename) return output
def script_main(session): supported_os = ["IOS", "NXOS"] if session.os not in supported_os: logger.debug("Unsupported OS: {0}. Exiting program.".format( session.os)) session.message_box("{0} is not a supported OS for this script.", "Unsupported OS", options=sessions.ICON_STOP) return send_cmd = "show interface" if session.os == "NXOS": template_file = "textfsm-templates/cisco_nxos_show_interface.template" else: template_file = "textfsm-templates/cisco_ios_show_interfaces.template" raw_intf = session.get_command_output(send_cmd) fsm_results = utils.textfsm_parse_to_list(raw_intf, template_file, add_header=True) output_filename = session.create_output_filename("int-stats", ext=".csv") utils.list_of_lists_to_csv(fsm_results, output_filename) # Clean up before closing session session.end()
def script_main(session): """ | SINGLE device script | Morphed: Gordon Rogier [email protected] | Framework: Jamie Caesar [email protected] This script will capture the WLC AireOS ap summary table and returns an output list :param session: A subclass of the sessions.Session object that represents this particular script session (either SecureCRTSession or DirectSession) :type session: sessions.Session """ # Get script object that owns this session, so we can check settings, get textfsm templates, etc script = session.script # Start session with device, i.e. modify term parameters for better interaction (assuming already connected) session.start_cisco_session() # Validate device is running a supported OS session.validate_os(["AireOS"]) # Get additional information we'll need ap_summ_table = get_ap_summ_table(session) # TODO grogier show ap config general extract output_filename = session.create_output_filename("ap-summ", ext=".csv") utilities.list_of_lists_to_csv(ap_summ_table, output_filename) # Return terminal parameters back to the original state. session.end_cisco_session()
def script_main(session): supported_os = ["IOS", "NXOS"] if session.os not in supported_os: logger.debug("Unsupported OS: {0}. Exiting program.".format( session.os)) session.message_box( "{0} is not a supported OS for this script.".format(session.os), "Unsupported OS", options=sessions.ICON_STOP) return if session.os == "IOS": send_cmd = "show vlan brief" template_file = "textfsm-templates/cisco_ios_show_vlan.template" else: send_cmd = "show vlan brief" template_file = "textfsm-templates/cisco_nxos_show_vlan.template" logger.debug("Using template file: {0}".format(template_file)) raw_vlan = session.get_command_output(send_cmd) fsm_results = utils.textfsm_parse_to_list(raw_vlan, template_file, add_header=True) normalize_port_list(fsm_results) output_filename = session.create_output_filename("vlan", ext=".csv") utils.list_of_lists_to_csv(fsm_results, output_filename) # Clean up before closing session session.end()
def script_main(session): """ | SINGLE device script | Author: Jamie Caesar | Email: [email protected] This script will capture the ARP table of the attached device and output the results as a CSV file. While this script can be used to capture the ARP table, the primary purpose is to create the ARP associations that the "s_switchport_mapping.py" script can use to map which MAC and IP addresses are connected to each device. :param session: A subclass of the sessions.Session object that represents this particular script session (either SecureCRTSession or DirectSession) :type session: sessions.Session """ # Get script object that owns this session, so we can check settings, get textfsm templates, etc script = session.script # Start session with device, i.e. modify term parameters for better interaction (assuming already connected) session.start_cisco_session() # Validate device is running a supported OS session.validate_os(["IOS", "NXOS"]) # Prompt for the VRF selected_vrf = script.prompt_window("Enter the VRF name.\n(Leave blank for default VRF)") if selected_vrf == "": selected_vrf = None logger.debug("Set VRF to '{0}'".format(selected_vrf)) # Select template file based on network OS if session.os == "IOS": send_cmd = "show ip arp" template_file = script.get_template("cisco_ios_show_ip_arp.template") else: send_cmd = "show ip arp detail" template_file = script.get_template("cisco_nxos_show_ip_arp_detail.template") logger.debug("Command set to '{0}'".format(send_cmd)) # If a VRF was specified, update the commands and outputs to reflect this. if selected_vrf: send_cmd = send_cmd + " vrf {0}".format(selected_vrf) session.hostname = session.hostname + "-VRF-{0}".format(selected_vrf) logger.debug("Updated hostname to: '{0}'".format(session.hostname)) # Get "show ip arp" data raw_arp = session.get_command_output(send_cmd) # Process with TextFSM logger.debug("Using template: '{0}'".format(template_file)) fsm_results = utilities.textfsm_parse_to_list(raw_arp, template_file, add_header=True) # Generate filename and output data as CSV output_filename = session.create_output_filename("arp", ext=".csv") utilities.list_of_lists_to_csv(fsm_results, output_filename) # Return terminal parameters back to the original state. session.end_cisco_session()
def script_main(session): """ | SINGLE device script | Author: Jamie Caesar | Email: [email protected] This script will capture the ARP table of the attached device and output the results as a CSV file. While this script can be used to capture the ARP table, the primary purpose is to create the ARP associations that the "s_switchport_mapping.py" script can use to map which MAC and IP addresses are connected to each device. :param session: A subclass of the sessions.Session object that represents this particular script session (either SecureCRTSession or DirectSession) :type session: sessions.Session """ # Get script object that owns this session, so we can check settings, get textfsm templates, etc script = session.script # Start session with device, i.e. modify term parameters for better interaction (assuming already connected) session.start_cisco_session() # Validate device is running a supported OS session.validate_os(["IOS", "NXOS"]) # Prompt for the VRF selected_vrf = script.prompt_window("Enter the VRF name.\n(Leave blank for default VRF)") if selected_vrf == "": selected_vrf = None logger.debug("Set VRF to '{0}'".format(selected_vrf)) # Select template file based on network OS if session.os == "IOS": send_cmd = "show ip arp" template_file = script.get_template("cisco_ios_show_ip_arp.template") else: send_cmd = "show ip arp detail" template_file = script.get_template("cisco_nxos_show_ip_arp_detail.template") logger.debug("Command set to '{0}'".format(send_cmd)) # If a VRF was specified, update the commands and outputs to reflect this. if selected_vrf: send_cmd = send_cmd + " vrf {0}".format(selected_vrf) session.hostname = session.hostname + "-VRF-{0}".format(selected_vrf) logger.debug("Updated hostname to: '{0}'".format(session.hostname)) # Get "show ip arp" data raw_arp = session.get_command_output(send_cmd) # Process with TextFSM logger.debug("Using template: '{0}'".format(template_file)) fsm_results = utilities.textfsm_parse_to_list(raw_arp, template_file, add_header=True) # Generate filename and output data as CSV output_filename = session.create_output_filename("arp", ext=".csv") utilities.list_of_lists_to_csv(fsm_results, output_filename) # Return terminal parameters back to the original state. session.end_cisco_session()
def script_main(session): """ | SINGLE device script | Author: Jamie Caesar | Email: [email protected] This script will grab the detailed CDP information from a Cisco IOS or NX-OS device and export it to a CSV file containing the important information, such as Remote Device hostname, model and IP information, in addition to the local and remote interfaces that connect the devices. **Script Settings** (found in settings/settings.ini): * | **strip_domains** - A list of domain names that will be stripped away if found in the CDP remote device name. :param session: A subclass of the sessions.Session object that represents this particular script session (either SecureCRTSession or DirectSession) :type session: sessions.Session """ # Get script object that owns this session, so we can check settings, get textfsm templates, etc script = session.script # Start session with device, i.e. modify term parameters for better interaction (assuming already connected) session.start_cisco_session() # Validate device is running a supported OS session.validate_os(["IOS", "NXOS"]) # Define the command to send to the remote device send_cmd = "show cdp neighbors detail" logger.debug("Command set to '{0}'".format(send_cmd)) # Get domain names to strip from device IDs from settings file strip_list = script.settings.getlist("cdp_to_csv", "strip_domains") # Get the output from our above command raw_cdp = session.get_command_output(send_cmd) # Choose the TextFSM template and process the data template_file = script.get_template("cisco_os_show_cdp_neigh_det.template") fsm_results = utilities.textfsm_parse_to_list(raw_cdp, template_file, add_header=True) # Since "System Name" is a newer NXOS feature -- try to extract it from the device ID when its empty. for entry in fsm_results[1:]: # entry[2] is system name, entry[1] is device ID if entry[2] == "": entry[2] = utilities.extract_system_name(entry[1], strip_list=strip_list) # Convert list of IPs into a comma-separated list of IPs entry[4] = ", ".join(entry[4]) # Convert list of Mgmt IPs into a comma-separated list of IPs entry[7] = ", ".join(entry[7]) output_filename = session.create_output_filename("cdp", ext=".csv") utilities.list_of_lists_to_csv(fsm_results, output_filename) # Return terminal parameters back to the original state. session.end_cisco_session()
def script_main(session, ask_vrf=True, vrf=None): """ | SINGLE device script | Author: Jamie Caesar | Email: [email protected] This script will grab the route table information from a Cisco IOS or NXOS device and export details about each next-hop address (how many routes and from which protocol) into a CSV file. It will also list all connected networks and give a detailed breakdown of every route that goes to each next-hop. :param session: A subclass of the sessions.Session object that represents this particular script session (either SecureCRTSession or DirectSession) :type session: sessions.Session :param ask_vrf: A boolean that specifies if we should prompt for which VRF. The default is true, but when this module is called from other scripts, we may want avoid prompting and supply the VRF with the "vrf" input. :type ask_vrf: bool :param vrf: The VRF that we should get the route table from. This is used only when ask_vrf is False. :type vrf: str """ # Get script object that owns this session, so we can check settings, get textfsm templates, etc script = session.script # Start session with device, i.e. modify term parameters for better interaction (assuming already connected) session.start_cisco_session() # Validate device is running a supported OS session.validate_os(["IOS", "NXOS"]) # If we should prompt for a VRF, then do so. Otherwise use the VRF passed into the function (if any) if ask_vrf: selected_vrf = script.prompt_window("Enter the VRF name. (Leave blank for default VRF)") else: selected_vrf = vrf # If we have a VRF, modify our commands and hostname to reflect it. If not, pull the default route table. if selected_vrf: send_cmd = "show ip route vrf {0}".format(selected_vrf) session.hostname = session.hostname + "-VRF-{0}".format(selected_vrf) logger.debug("Received VRF: {0}".format(selected_vrf)) else: send_cmd = "show ip route" raw_routes = session.get_command_output(send_cmd) if session.os == "IOS": template_file = script.get_template("cisco_ios_show_ip_route.template") else: template_file = script.get_template("cisco_nxos_show_ip_route.template") fsm_results = utilities.textfsm_parse_to_dict(raw_routes, template_file) route_list = parse_routes(fsm_results) output_filename = session.create_output_filename("nexthop-summary", ext=".csv") output = nexthop_summary(route_list) utilities.list_of_lists_to_csv(output, output_filename) # Return terminal parameters back to the original state. session.end_cisco_session()
def script_main(session): """ | SINGLE device script | Author: Jamie Caesar | Email: [email protected] This script will grab the detailed CDP information from a Cisco IOS or NX-OS device and export it to a CSV file containing the important information, such as Remote Device hostname, model and IP information, in addition to the local and remote interfaces that connect the devices. **Script Settings** (found in settings/settings.ini): * | **strip_domains** - A list of domain names that will be stripped away if found in the CDP remote device name. :param session: A subclass of the sessions.Session object that represents this particular script session (either SecureCRTSession or DirectSession) :type session: sessions.Session """ # Get script object that owns this session, so we can check settings, get textfsm templates, etc script = session.script # Start session with device, i.e. modify term parameters for better interaction (assuming already connected) session.start_cisco_session() # Validate device is running a supported OS session.validate_os(["IOS", "NXOS"]) # Define the command to send to the remote device send_cmd = "show cdp neighbors detail" logger.debug("Command set to '{0}'".format(send_cmd)) # Get domain names to strip from device IDs from settings file strip_list = script.settings.getlist("cdp_to_csv", "strip_domains") # Get the output from our above command raw_cdp = session.get_command_output(send_cmd) # Choose the TextFSM template and process the data template_file = script.get_template("cisco_os_show_cdp_neigh_det.template") fsm_results = utilities.textfsm_parse_to_list(raw_cdp, template_file, add_header=True) # Since "System Name" is a newer NXOS feature -- try to extract it from the device ID when its empty. for entry in fsm_results[1:]: # entry[2] is system name, entry[1] is device ID if entry[2] == "": entry[2] = utilities.extract_system_name(entry[1], strip_list=strip_list) # Convert list of IPs into a comma-separated list of IPs entry[4] = ", ".join(entry[4]) # Convert list of Mgmt IPs into a comma-separated list of IPs entry[7] = ", ".join(entry[7]) output_filename = session.create_output_filename("cdp", ext=".csv") utilities.list_of_lists_to_csv(fsm_results, output_filename) # Return terminal parameters back to the original state. session.end_cisco_session()
def script_main(session): """ | SINGLE device script | Author: Jamie Caesar | Email: [email protected] This script will grab the MAC address table from a Cisco IOS or NX-OS device and export it to a CSV file. :param session: A subclass of the sessions.Session object that represents this particular script session (either SecureCRTSession or DirectSession) :type session: sessions.Session """ # Get script object that owns this session, so we can check settings, get textfsm templates, etc script = session.script # Start session with device, i.e. modify term parameters for better interaction (assuming already connected) session.start_cisco_session() # Validate device is running a supported OS session.validate_os(["IOS", "NXOS"]) # TextFSM template for parsing "show mac address-table" output if session.os == "NXOS": template_file = script.get_template("cisco_nxos_show_mac_addr_table.template") else: template_file = script.get_template("cisco_ios_show_mac_addr_table.template") raw_mac = session.get_command_output("show mac address-table") fsm_results = utilities.textfsm_parse_to_list(raw_mac, template_file, add_header=True) # Check if IOS mac_table is empty -- if so, it is probably because the switch has an older IOS # that expects "show mac-address-table" instead of "show mac address-table". if session.os == "IOS" and len(fsm_results) == 1: send_cmd = "show mac-address-table dynamic" logger.debug("Retrying with command set to '{0}'".format(send_cmd)) raw_mac = session.get_command_output(send_cmd) fsm_results = utilities.textfsm_parse_to_list(raw_mac, template_file, add_header=True) output_filename = session.create_output_filename("mac-addr", ext=".csv") utilities.list_of_lists_to_csv(fsm_results, output_filename) # Return terminal parameters back to the original state. session.end_cisco_session()
def script_main(session): supported_os = ["IOS", "NXOS"] if session.os not in supported_os: logger.debug("Unsupported OS: {0}. Exiting program.".format( session.os)) session.message_box( "{0} is not a supported OS for this script.".format(session.os), "Unsupported OS", options=sessions.ICON_STOP) return selected_vrf = session.prompt_window( "Enter the VRF name.\n(Leave blank for default VRF)") if selected_vrf == "": selected_vrf = None logger.debug("Set VRF to '{0}'".format(selected_vrf)) if session.os == "IOS": send_cmd = "show ip arp" template_file = "textfsm-templates/cisco_ios_show_ip_arp.template" else: send_cmd = "show ip arp detail" template_file = "textfsm-templates/cisco_nxos_show_ip_arp_detail.template" logger.debug("Command set to '{0}'".format(send_cmd)) if selected_vrf: send_cmd = send_cmd + " vrf {0}".format(selected_vrf) session.hostname = session.hostname + "-VRF-{0}".format(selected_vrf) logger.debug("Updated hostname to: '{0}'".format(session.hostname)) raw_arp = session.get_command_output(send_cmd) logger.debug("Using template: '{0}'".format(template_file)) fsm_results = utils.textfsm_parse_to_list(raw_arp, template_file, add_header=True) output_filename = session.create_output_filename("arp", ext=".csv") utils.list_of_lists_to_csv(fsm_results, output_filename) # Clean up before closing session session.end()
def script_main(session): supported_os = ["IOS", "NXOS"] if session.os not in supported_os: logger.debug("Unsupported OS: {0}. Exiting program.".format( session.os)) session.message_box( "{0} is not a supported OS for this script.".format(session.os), "Unsupported OS", options=sessions.ICON_STOP) return send_cmd = "show mac address-table" # TextFSM template for parsing "show mac address-table" output if session.os == "NXOS": template_file = "textfsm-templates/cisco_nxos_show_mac_addr_table.template" else: template_file = "textfsm-templates/cisco_ios_show_mac_addr_table.template" logger.debug("Using template: '{0}'".format(template_file)) raw_mac = session.get_command_output(send_cmd) fsm_results = utils.textfsm_parse_to_list(raw_mac, template_file, add_header=True) # Check if IOS mac_table is empty -- if so, it is probably because the switch has an older IOS # that expects "show mac-address-table" instead of "show mac address-table". if session.os == "IOS" and len(fsm_results) == 1: send_cmd = "show mac-address-table dynamic" logger.debug("Retrying with command set to '{0}'".format(send_cmd)) raw_mac = session.get_command_output(send_cmd) fsm_results = utils.textfsm_parse_to_list(raw_mac, template_file, add_header=True) output_filename = session.create_output_filename("mac-addr", ext=".csv") utils.list_of_lists_to_csv(fsm_results, output_filename) # Clean up before closing session session.end()
def script_main(session): """ | SINGLE device script | Author: Jamie Caesar | Email: [email protected] This script will scrape some stats (packets, rate, errors) from all the UP interfaces on the device and put it into a CSV file. :param session: A subclass of the sessions.Session object that represents this particular script session (either SecureCRTSession or DirectSession) :type session: sessions.Session """ # Get script object that owns this session, so we can check settings, get textfsm templates, etc script = session.script # Start session with device, i.e. modify term parameters for better interaction (assuming already connected) session.start_cisco_session() # Validate device is running a supported OS session.validate_os(["IOS", "NXOS"]) # Get correct TextFSM template based on remote device OS if session.os == "NXOS": template_file = script.get_template( "cisco_nxos_show_interface.template") else: template_file = script.get_template( "cisco_ios_show_interfaces.template") # Get raw output from the device raw_intf = session.get_command_output("show interface") # Process the output with TextFSM fsm_results = utilities.textfsm_parse_to_list(raw_intf, template_file, add_header=True) # Create output filename output_filename = session.create_output_filename("int-stats", ext=".csv") # Write output to a CSV file utilities.list_of_lists_to_csv(fsm_results, output_filename) # Return terminal parameters back to the original state. session.end_cisco_session()
def script_main(session): """ | SINGLE device script | Author: Jamie Caesar | Email: [email protected] This script will output the VLAN database to a CSV file. One possibly use of this script is to take the .CSV outputs from 2 or more devices, paste them into a single XLS file and use Excel to highlight duplicate values, so VLAN overlaps can be discovered prior to connecting switches together via direct link, OTV, etc. This could also be used to find missing VLANs between 2 large tables that should have the same VLANs. :param session: A subclass of the sessions.Session object that represents this particular script session (either SecureCRTSession or DirectSession) :type session: sessions.Session """ # Get script object that owns this session, so we can check settings, get textfsm templates, etc script = session.script # Start session with device, i.e. modify term parameters for better interaction (assuming already connected) session.start_cisco_session() # Validate device is running a supported OS session.validate_os(["IOS", "NXOS"]) if session.os == "IOS": template_file = script.get_template("cisco_ios_show_vlan.template") else: template_file = script.get_template("cisco_nxos_show_vlan.template") raw_vlan = session.get_command_output("show vlan brief") fsm_results = utilities.textfsm_parse_to_list(raw_vlan, template_file, add_header=True) normalize_port_list(fsm_results) output_filename = session.create_output_filename("vlan", ext=".csv") utilities.list_of_lists_to_csv(fsm_results, output_filename) # Return terminal parameters back to the original state. session.end_cisco_session()
def script_main(session): """ | SINGLE device script | Author: Jamie Caesar | Email: [email protected] This script will scrape some stats (packets, rate, errors) from all the UP interfaces on the device and put it into a CSV file. :param session: A subclass of the sessions.Session object that represents this particular script session (either SecureCRTSession or DirectSession) :type session: sessions.Session """ # Get script object that owns this session, so we can check settings, get textfsm templates, etc script = session.script # Start session with device, i.e. modify term parameters for better interaction (assuming already connected) session.start_cisco_session() # Validate device is running a supported OS session.validate_os(["IOS", "NXOS"]) # Get correct TextFSM template based on remote device OS if session.os == "NXOS": template_file = script.get_template("cisco_nxos_show_interface.template") else: template_file = script.get_template("cisco_ios_show_interfaces.template") # Get raw output from the device raw_intf = session.get_command_output("show interface") # Process the output with TextFSM fsm_results = utilities.textfsm_parse_to_list(raw_intf, template_file, add_header=True) # Create output filename output_filename = session.create_output_filename("int-stats", ext=".csv") # Write output to a CSV file utilities.list_of_lists_to_csv(fsm_results, output_filename) # Return terminal parameters back to the original state. session.end_cisco_session()
def get_interface_detail(session, to_cvs=False): """ A function that captures the WLC AireOS interface detail table and returns an output list :param session: The script object that represents this script being executed :type session: session.Session :return: A list of interface details :rtype: list of lists """ send_cmd = "show interface summary" output_raw = session.get_command_output(send_cmd) # TextFSM template for parsing "show interface summary" output template_file = session.script.get_template( "cisco_aireos_show_interface_summary.template") interface_summ_dict = utilities.textfsm_parse_to_dict( output_raw, template_file) output_raw = '' for interface_entry in interface_summ_dict: send_cmd = "show interface detailed " + format( interface_entry["INT_Name"]) output_raw += session.get_command_output(send_cmd) # TextFSM template for parsing "show interface detailed <interface-name>" output template_file = session.script.get_template( "cisco_aireos_show_interface_detailed.template") output = utilities.textfsm_parse_to_list(output_raw, template_file, add_header=True) if to_cvs: output_filename = session.create_output_filename("interface-detail", ext=".csv") utilities.list_of_lists_to_csv(output, output_filename) return output
def script_main(session): supported_os = ["IOS", "NXOS"] if session.os not in supported_os: logger.debug("Unsupported OS: {0}. Exiting program.".format( session.os)) session.message_box( "{0} is not a supported OS for this script.".format(session.os), "Unsupported OS", options=sessions.ICON_STOP) return else: send_cmd = "show ip route" selected_vrf = session.prompt_window( "Enter the VRF name. (Leave blank for default VRF)") if selected_vrf != "": send_cmd = send_cmd + " vrf {0}".format(selected_vrf) session.hostname = session.hostname + "-VRF-{0}".format(selected_vrf) logger.debug("Received VRF: {0}".format(selected_vrf)) raw_routes = session.get_command_output(send_cmd) if session.os == "IOS": template_file = "textfsm-templates/cisco_ios_show_ip_route.template" else: template_file = "textfsm-templates/cisco_nxos_show_ip_route.template" fsm_results = utils.textfsm_parse_to_dict(raw_routes, template_file) route_list = parse_routes(fsm_results) output_filename = session.create_output_filename("nexthop-summary", ext=".csv") output = nexthop_summary(route_list) utils.list_of_lists_to_csv(output, output_filename) # Clean up before closing session session.end()
def script_main(session): supported_os = ["IOS", "NXOS"] if session.os not in supported_os: logger.debug("Unsupported OS: {0}. Exiting program.".format( session.os)) session.message_box( "{0} is not a supported OS for this script.".format(session.os), "Unsupported OS", options=sessions.ICON_STOP) return send_cmd = "show cdp neighbors detail" logger.debug("Command set to '{0}'".format(send_cmd)) raw_cdp = session.get_command_output(send_cmd) template_file = "textfsm-templates/cisco_os_show_cdp_neigh_det.template" logger.debug("Using template: '{0}'".format(template_file)) fsm_results = utils.textfsm_parse_to_list(raw_cdp, template_file, add_header=True) # Since "System Name" is a newer NXOS feature -- try to extract it from the device ID when its empty. for entry in fsm_results: # entry[2] is system name, entry[1] is device ID if entry[2] == "": entry[2] = utils.extract_system_name( entry[1], strip_list=local_settings['strip_domains']) output_filename = session.create_output_filename("cdp", ext=".csv") utils.list_of_lists_to_csv(fsm_results, output_filename) # Clean up before closing session session.end()
def script_main(script): """ | MULTIPLE device script | Author: Jamie Caesar | Email: [email protected] This script will pull the ARP tables from multiple devices and combine their data into a single ARP CSV file. The main intention for this script is to be used with the 's_switchport_mapping' script, which will prompt for an ARP table CSV file to list IPs connected to switch ports. This script is intended to speed up the collection of ARP data in cases such as: 1) There are 2 core switches running a first hop redundancy protocol (HSRP, GLBP, etc) and both devices are actively passing traffic so we need both ARP tables 2) The switch has VLANs that are being used in multiple upstream VRFs (not all with SVIs on the same devices) so the ARP tables from many devices may be needed to fully map the switch. **NOTE**: Since this script merges ARP tables of multiple devices which may have duplicate entries, the interface is NOT written to the output file like it is with the single device version of this script. This script checks that it will NOT be run in a connected tab. This script initiates the connection to all devices based on the input of the device CSV file that the script requests. :param script: A subclass of the scripts.Script object that represents the execution of this particular script (either CRTScript or DirectScript) :type script: scripts.Script """ session = script.get_main_session() # If this is launched on an active tab, disconnect before continuing. logger.debug("<M_SCRIPT> Checking if current tab is connected.") if session.is_connected(): logger.debug("<M_SCRIPT> Existing tab connected. Stopping execution.") raise scripts.ScriptError("This script must be launched in a not-connected tab.") # Load a device list device_list = script.import_device_list() if not device_list: return # Prompt for the VRF selected_vrf = script.prompt_window("Enter the VRF name.\n(Leave blank for default VRF)") if selected_vrf == "": selected_vrf = None logger.debug("Set VRF to '{0}'".format(selected_vrf)) # Check settings if we should use a proxy/jumpbox use_proxy = script.settings.getboolean("Global", "use_proxy") default_proxy_session = script.settings.get("Global", "proxy_session") # ######################################## START DEVICE CONNECT LOOP ########################################### # Create a filename to keep track of our connection logs, if we have failures. Use script name without extension failed_log = session.create_output_filename("{0}-LOG".format(script_name.split(".")[0]), include_hostname=False) arp_collection = [] for device in device_list: hostname = device['Hostname'] protocol = device['Protocol'] username = device['Username'] password = device['Password'] enable = device['Enable'] try: proxy = device['Proxy Session'] except KeyError: proxy = None if not proxy and use_proxy: proxy = default_proxy_session logger.debug("<M_SCRIPT> Connecting to {0}.".format(hostname)) try: script.connect(hostname, username, password, protocol=protocol, proxy=proxy) session = script.get_main_session() arp_collection.extend(per_device_work(session, selected_vrf, add_header=False)) script.disconnect() except scripts.ConnectError as e: with open(failed_log, 'a') as logfile: logfile.write("<M_SCRIPT> Connect to {0} failed: {1}\n".format(hostname, e.message.strip())) session.disconnect() except sessions.InteractionError as e: with open(failed_log, 'a') as logfile: logfile.write("<M_SCRIPT> Failure on {0}: {1}\n".format(hostname, e.message.strip())) session.disconnect() except sessions.UnsupportedOSError as e: with open(failed_log, 'a') as logfile: logfile.write("<M_SCRIPT> Unsupported OS on {0}: {1}\n".format(hostname, e.message.strip())) session.disconnect() except Exception as e: with open(failed_log, 'a') as logfile: logfile.write("<M_SCRIPT> Exception on {0}: {1} ({2})\n".format(hostname, e.message.strip(), e)) session.disconnect() # ######################################### END DEVICE CONNECT LOOP ############################################ # ######################################### PROCESS COLLECTED DATA ############################################# # Build a combined table without duplicate values from the data retrieved from all devices. combined_table = [] seen = set() for entry in arp_collection: if entry[2] not in seen: combined_table.append([entry[0], "", entry[2], entry[3], ""]) seen.add(entry[2]) combined_table.sort(key=lambda x: utilities.human_sort_key(x[0])) combined_table.insert(0, ["IP ADDRESS", "", "MAC ADDRESS", "VLAN", ""]) # Generate filename and output data as CSV output_filename = session.create_output_filename("merged-arp", include_hostname=False, ext=".csv") utilities.list_of_lists_to_csv(combined_table, output_filename)
def script_main(session, ask_vrf=True, vrf=None): """ | SINGLE device script | Author: Jamie Caesar | Email: [email protected] This script will grab the EIGRP topology from a Cisco IOS or NXOS device and export a summary of how many networks are learned from each successor/feasible successor and output it into a CSV file. It will also give a detailed breakdown of every network that was learned from a particular successor :param session: A subclass of the sessions.Session object that represents this particular script session (either SecureCRTSession or DirectSession) :type session: sessions.Session :param ask_vrf: A boolean that specifies if we should prompt for which VRF. The default is true, but when this module is called from other scripts, we may want avoid prompting and supply the VRF with the "vrf" input. :type ask_vrf: bool :param vrf: The VRF that we should get the route table from. This is used only when ask_vrf is False. :type vrf: str """ # Get script object that owns this session, so we can check settings, get textfsm templates, etc script = session.script # Start session with device, i.e. modify term parameters for better interaction (assuming already connected) session.start_cisco_session() # Validate device is running a supported OS session.validate_os(["IOS", "NXOS"]) # If we should prompt for a VRF, then do so. Otherwise use the VRF passed into the function (if any) if ask_vrf: selected_vrf = script.prompt_window( "Enter the VRF name. (Leave blank for default VRF, 'all' for all VRFs)" ) selected_vrf = selected_vrf.strip() logger.debug("Input VRF: {0}".format(selected_vrf)) else: selected_vrf = vrf logger.debug("Received VRF: {0}".format(selected_vrf)) # If we have a VRF, modify our commands and hostname to reflect it. If not, pull the default route table. if selected_vrf: if session.os == "IOS": if selected_vrf == "all": send_cmd = "show ip eigrp vrf * topology" else: send_cmd = "show ip eigrp vrf {0} topology".format( selected_vrf) else: if selected_vrf == "*": send_cmd = "show ip eigrp topology vrf all" else: send_cmd = "show ip eigrp topology vrf {0}".format( selected_vrf) else: send_cmd = "show ip eigrp topology" logger.debug("Generated Command: {0}".format(send_cmd)) raw_topo = session.get_command_output(send_cmd) if session.os == "IOS": template_file = script.get_template( "cisco_ios_show_ip_eigrp_topology.template") else: template_file = script.get_template( "cisco_nxos_show_ip_eigrp_topology.template") fsm_results = utilities.textfsm_parse_to_dict(raw_topo, template_file) detailed_results = process_topology(fsm_results) for process, nexthops in detailed_results.iteritems(): nexthop_list = sorted(nexthops.keys(), key=utilities.human_sort_key) vrf = process[0] as_num = process[1] rid = process[2] output = [["Hostname:", session.hostname], ["VRF:", vrf], ["AS:", as_num], ["Router ID:", rid], ["", ""], ["Nexthop", "Routes Learned"]] # output.append(["EIGRP TOPOLOGY SUMMARY", ""]) for nexthop in nexthop_list: output.append([nexthop, len(nexthops[nexthop])]) output.append(["", ""]) # output.append(["DETAILED ROUTE LIST",""]) for nexthop in nexthop_list: output.append(["Nexthop", "Routes"]) sorted_networks = sorted(nexthops[nexthop], key=utilities.human_sort_key) for network in sorted_networks: output.append([nexthop, network]) output.append(["", ""]) if vrf: output_filename = session.create_output_filename( "{0}-eigrp-{1}-summary".format(vrf, as_num), ext=".csv") else: output_filename = session.create_output_filename( "-eigrp-{0}-summary".format(as_num), ext=".csv") utilities.list_of_lists_to_csv(output, output_filename) # Return terminal parameters back to the original state. session.end_cisco_session()
def script_main(script): """ | MULTIPLE device script | Author: Jamie Caesar | Email: [email protected] This script will pull the ARP tables from multiple devices and combine their data into a single ARP CSV file. The main intention for this script is to be used with the 's_switchport_mapping' script, which will prompt for an ARP table CSV file to list IPs connected to switch ports. This script is intended to speed up the collection of ARP data in cases such as: 1) There are 2 core switches running a first hop redundancy protocol (HSRP, GLBP, etc) and both devices are actively passing traffic so we need both ARP tables 2) The switch has VLANs that are being used in multiple upstream VRFs (not all with SVIs on the same devices) so the ARP tables from many devices may be needed to fully map the switch. NOTE: Since this script merges the ARP tables of multiple devices which may have duplicate entries, the interface is NOT written to the output file like it is with the single device version of this script. This script checks that it will NOT be run in a connected tab. This script initiates the connection to all devices based on the input of the device CSV file that the script requests. :param script: A subclass of the scripts.Script object that represents the execution of this particular script (either CRTScript or DirectScript) :type script: scripts.Script """ session = script.get_main_session() # If this is launched on an active tab, disconnect before continuing. logger.debug("<M_SCRIPT> Checking if current tab is connected.") if session.is_connected(): logger.debug("<M_SCRIPT> Existing tab connected. Stopping execution.") raise scripts.ScriptError( "This script must be launched in a not-connected tab.") # Load a device list device_list = script.import_device_list() if not device_list: return # Prompt for the VRF selected_vrf = script.prompt_window( "Enter the VRF name.\n(Leave blank for default VRF)") if selected_vrf == "": selected_vrf = None logger.debug("Set VRF to '{0}'".format(selected_vrf)) # Check settings if we should use a proxy/jumpbox use_proxy = script.settings.getboolean("Global", "use_proxy") default_proxy_session = script.settings.get("Global", "proxy_session") # ######################################## START DEVICE CONNECT LOOP ########################################### # Create a filename to keep track of our connection logs, if we have failures. Use script name without extension failed_log = session.create_output_filename("{0}-LOG".format( script_name.split(".")[0]), include_hostname=False) arp_collection = [] for device in device_list: hostname = device['hostname'] protocol = device['protocol'] username = device['username'] password = device['password'] enable = device['enable'] proxy = device['proxy'] if not proxy and use_proxy: proxy = default_proxy_session logger.debug("<M_SCRIPT> Connecting to {0}.".format(hostname)) try: session.connect(hostname, username, password, protocol=protocol, proxy=proxy) arp_collection.extend( per_device_work(session, selected_vrf, add_header=False)) session.disconnect() except sessions.ConnectError as e: with open(failed_log, 'a') as logfile: logfile.write("Connect to {0} failed: {1}\n".format( hostname, e.message.strip())) except sessions.InteractionError as e: with open(failed_log, 'a') as logfile: logfile.write("Failure on {0}: {1}\n".format( hostname, e.message.strip())) # ######################################### END DEVICE CONNECT LOOP ############################################ # ######################################### PROCESS COLLECTED DATA ############################################# # Build a combined table without duplicate values from the data retrieved from all devices. combined_table = [] seen = set() for entry in arp_collection: if entry[2] not in seen: combined_table.append([entry[0], "", entry[2], entry[3], ""]) seen.add(entry[2]) combined_table.sort(key=lambda x: utilities.human_sort_key(x[0])) combined_table.insert(0, ["IP ADDRESS", "", "MAC ADDRESS", "VLAN", ""]) # Generate filename and output data as CSV output_filename = session.create_output_filename("merged-arp", include_hostname=False, ext=".csv") utilities.list_of_lists_to_csv(combined_table, output_filename)
def script_main(session, ask_vrf=True, vrf=None): """ | SINGLE device script | Author: Jamie Caesar | Email: [email protected] This script will grab the EIGRP topology table from a Cisco IOS or NXOS device and export it as a CSV file. :param session: A subclass of the sessions.Session object that represents this particular script session (either SecureCRTSession or DirectSession) :type session: sessions.Session :param ask_vrf: A boolean that specifies if we should prompt for which VRF. The default is true, but when this module is called from other scripts, we may want avoid prompting and supply the VRF with the "vrf" input. :type ask_vrf: bool :param vrf: The VRF that we should get the route table from. This is used only when ask_vrf is False. :type vrf: str """ # Get script object that owns this session, so we can check settings, get textfsm templates, etc script = session.script # Start session with device, i.e. modify term parameters for better interaction (assuming already connected) session.start_cisco_session() # Validate device is running a supported OS session.validate_os(["IOS", "NXOS"]) # If we should prompt for a VRF, then do so. Otherwise use the VRF passed into the function (if any) if ask_vrf: selected_vrf = script.prompt_window("Enter the VRF name. (Leave blank for default VRF, 'all' for all VRFs)") logger.debug("Input VRF: {0}".format(selected_vrf)) else: selected_vrf = vrf logger.debug("Received VRF: {0}".format(selected_vrf)) # If we have a VRF, modify our commands and hostname to reflect it. If not, pull the default route table. if selected_vrf: if session.os == "IOS": if selected_vrf == "all": send_cmd = "show ip eigrp vrf * topology" session.hostname = session.hostname + "-VRF-all".format(selected_vrf) else: send_cmd = "show ip eigrp vrf {0} topology".format(selected_vrf) session.hostname = session.hostname + "-VRF-{0}".format(selected_vrf) else: send_cmd = "show ip eigrp topology vrf {0}".format(selected_vrf) session.hostname = session.hostname + "-VRF-{0}".format(selected_vrf) else: send_cmd = "show ip eigrp topology" logger.debug("Generated Command: {0}".format(send_cmd)) raw_topo = session.get_command_output(send_cmd) if session.os == "IOS": template_file = script.get_template("cisco_ios_show_ip_eigrp_topology.template") else: template_file = script.get_template("cisco_nxos_show_ip_eigrp_topology.template") fsm_results = utilities.textfsm_parse_to_list(raw_topo, template_file, add_header=True) output_filename = session.create_output_filename("eigrp-topo", ext=".csv") utilities.list_of_lists_to_csv(fsm_results, output_filename) # Return terminal parameters back to the original state. session.end_cisco_session()
def script_main(session, gateway_hostname=""): """ | SINGLE device script | Author: Jamie Caesar | Email: [email protected] This script will first prompt for the location of the ARP table to use for processing. Next, the mac address table of the active session will be captured and a CSV file showing the MAC address and IP of what is attached to each port on the device will be output. :param session: A subclass of the sessions.Session object that represents this particular script session (either SecureCRTSession or DirectSession) :type session: sessions.Session """ # Get script object that owns this session, so we can check settings, get textfsm templates, etc script = session.script # Start session with device, i.e. modify term parameters for better interaction (assuming already connected) session.start_cisco_session() # Validate device is running a supported OS session.validate_os(["IOS", "NXOS"]) # Get additional information we'll need int_table = get_int_status(session) mac_table = get_mac_table(session) desc_table = get_desc_table(session) arp_lookup = get_arp_info(script) output = [] for intf_entry in int_table: intf = intf_entry[0] # Exclude VLAN interfaces if intf.lower().startswith("v"): continue state = intf_entry[2] # Get interface description, if one exists desc = None if intf in desc_table.keys(): desc = desc_table[intf] # Record upsteam information for routed ports if intf_entry[3] == 'routed': vlan = intf_entry[3] mac = None ip = None fqdn = None mac_vendor = None if intf in arp_lookup.keys(): arp_list = arp_lookup[intf] for entry in arp_list: mac, ip = entry if mac and mac_lookup: mac_vendor = mac_to_vendor(mac) if dns_lookup and ip: try: fqdn, _, _, = socket.gethostbyaddr(ip) except socket.herror: pass output_line = [ intf, state, mac, mac_vendor, fqdn, ip, vlan, desc ] output.append(output_line) else: output_line = [ intf, state, mac, mac_vendor, fqdn, ip, vlan, desc ] output.append(output_line) # Record all information for L2 ports elif intf in mac_table.keys(): for mac_entry in mac_table[intf]: mac, vlan = mac_entry ip = None fqdn = None mac_vendor = None if mac and mac in arp_lookup.keys(): for entry in arp_lookup[mac]: ip, arp_vlan = entry if vlan == arp_vlan: if mac and mac_lookup: mac_vendor = mac_to_vendor(mac) if dns_lookup and ip: try: fqdn, _, _, = socket.gethostbyaddr(ip) except socket.herror: pass output_line = [ intf, state, mac, mac_vendor, fqdn, ip, vlan, desc ] output.append(output_line) else: output_line = [ intf, state, mac, mac_vendor, fqdn, ip, vlan, desc ] output.append(output_line) else: output_line = [intf, state, None, None, None, None, None, desc] output.append(output_line) output.sort(key=lambda x: utilities.human_sort_key(x[0])) output.insert(0, [ "Interface", "Status", "MAC", "MAC Vendor", "DNS Name", "IP Address", "VLAN", "Description" ]) output_filename = session.create_output_filename("PortMap", ext=".csv") utilities.list_of_lists_to_csv(output, output_filename) # Return terminal parameters back to the original state. session.end_cisco_session()
def script_main(session, ask_vrf=True, vrf=None): """ | SINGLE device script | Author: Jamie Caesar | Email: [email protected] This script will grab the route table information from a Cisco IOS or NXOS device and export details about each next-hop address (how many routes and from which protocol) into a CSV file. It will also list all connected networks and give a detailed breakdown of every route that goes to each next-hop. :param session: A subclass of the sessions.Session object that represents this particular script session (either SecureCRTSession or DirectSession) :type session: sessions.Session :param ask_vrf: A boolean that specifies if we should prompt for which VRF. The default is true, but when this module is called from other scripts, we may want avoid prompting and supply the VRF with the "vrf" input. :type ask_vrf: bool :param vrf: The VRF that we should get the route table from. This is used only when ask_vrf is False. :type vrf: str """ # Get script object that owns this session, so we can check settings, get textfsm templates, etc script = session.script # Start session with device, i.e. modify term parameters for better interaction (assuming already connected) session.start_cisco_session() # Validate device is running a supported OS session.validate_os(["IOS", "NXOS"]) # If we should prompt for a VRF, then do so. Otherwise use the VRF passed into the function (if any) if ask_vrf: selected_vrf = script.prompt_window( "Enter the VRF name. (Leave blank for default VRF)") else: selected_vrf = vrf # If we have a VRF, modify our commands and hostname to reflect it. If not, pull the default route table. if selected_vrf: send_cmd = "show ip route vrf {0}".format(selected_vrf) session.hostname = session.hostname + "-VRF-{0}".format(selected_vrf) logger.debug("Received VRF: {0}".format(selected_vrf)) else: send_cmd = "show ip route" raw_routes = session.get_command_output(send_cmd) if session.os == "IOS": template_file = script.get_template("cisco_ios_show_ip_route.template") else: template_file = script.get_template( "cisco_nxos_show_ip_route.template") fsm_results = utilities.textfsm_parse_to_dict(raw_routes, template_file) route_list = parse_routes(fsm_results) output_filename = session.create_output_filename("nexthop-summary", ext=".csv") output = nexthop_summary(route_list) utilities.list_of_lists_to_csv(output, output_filename) # Return terminal parameters back to the original state. session.end_cisco_session()
def script_main(session, ask_vrf=True, vrf=None): """ | SINGLE device script | Author: Jamie Caesar | Email: [email protected] This script will grab the EIGRP topology table from a Cisco IOS or NXOS device and export it as a CSV file. :param session: A subclass of the sessions.Session object that represents this particular script session (either SecureCRTSession or DirectSession) :type session: sessions.Session :param ask_vrf: A boolean that specifies if we should prompt for which VRF. The default is true, but when this module is called from other scripts, we may want avoid prompting and supply the VRF with the "vrf" input. :type ask_vrf: bool :param vrf: The VRF that we should get the route table from. This is used only when ask_vrf is False. :type vrf: str """ # Get script object that owns this session, so we can check settings, get textfsm templates, etc script = session.script # Start session with device, i.e. modify term parameters for better interaction (assuming already connected) session.start_cisco_session() # Validate device is running a supported OS session.validate_os(["IOS", "NXOS"]) # If we should prompt for a VRF, then do so. Otherwise use the VRF passed into the function (if any) if ask_vrf: selected_vrf = script.prompt_window( "Enter the VRF name. (Leave blank for default VRF, 'all' for all VRFs)" ) logger.debug("Input VRF: {0}".format(selected_vrf)) else: selected_vrf = vrf logger.debug("Received VRF: {0}".format(selected_vrf)) # If we have a VRF, modify our commands and hostname to reflect it. If not, pull the default route table. if selected_vrf: if session.os == "IOS": if selected_vrf == "all": send_cmd = "show ip eigrp vrf * topology" session.hostname = session.hostname + "-VRF-all".format( selected_vrf) else: send_cmd = "show ip eigrp vrf {0} topology".format( selected_vrf) session.hostname = session.hostname + "-VRF-{0}".format( selected_vrf) else: send_cmd = "show ip eigrp topology vrf {0}".format(selected_vrf) session.hostname = session.hostname + "-VRF-{0}".format( selected_vrf) else: send_cmd = "show ip eigrp topology" logger.debug("Generated Command: {0}".format(send_cmd)) raw_topo = session.get_command_output(send_cmd) if session.os == "IOS": template_file = script.get_template( "cisco_ios_show_ip_eigrp_topology.template") else: template_file = script.get_template( "cisco_nxos_show_ip_eigrp_topology.template") fsm_results = utilities.textfsm_parse_to_list(raw_topo, template_file, add_header=True) output_filename = session.create_output_filename("eigrp-topo", ext=".csv") utilities.list_of_lists_to_csv(fsm_results, output_filename) # Return terminal parameters back to the original state. session.end_cisco_session()
def script_main(session, gateway_hostname=""): """ | SINGLE device script | Author: Jamie Caesar | Email: [email protected] This script will first prompt for the location of the ARP table to use for processing. Next, the mac address table of the active session will be captured and a CSV file showing the MAC address and IP of what is attached to each port on the device will be output. :param session: A subclass of the sessions.Session object that represents this particular script session (either SecureCRTSession or DirectSession) :type session: sessions.Session """ # Get script object that owns this session, so we can check settings, get textfsm templates, etc script = session.script # Start session with device, i.e. modify term parameters for better interaction (assuming already connected) session.start_cisco_session() # Validate device is running a supported OS session.validate_os(["IOS", "NXOS"]) # Get additional information we'll need int_table = get_int_status(session) mac_table = get_mac_table(session) desc_table = get_desc_table(session) arp_lookup = get_arp_info(script) output = [] for intf_entry in int_table: intf = intf_entry[0] # Exclude VLAN interfaces if intf.lower().startswith("v"): continue state = intf_entry[2] # Get interface description, if one exists desc = None if intf in desc_table.keys(): desc = desc_table[intf] # Record upsteam information for routed ports if intf_entry[3] == 'routed': vlan = intf_entry[3] mac = None ip = None fqdn = None mac_vendor = None if intf in arp_lookup.keys(): arp_list = arp_lookup[intf] for entry in arp_list: mac, ip = entry if mac and mac_lookup: mac_vendor = mac_to_vendor(mac) if dns_lookup and ip: try: fqdn, _, _, = socket.gethostbyaddr(ip) except socket.herror: pass output_line = [intf, state, mac, mac_vendor, fqdn, ip, vlan, desc] output.append(output_line) else: output_line = [intf, state, mac, mac_vendor, fqdn, ip, vlan, desc] output.append(output_line) # Record all information for L2 ports elif intf in mac_table.keys(): for mac_entry in mac_table[intf]: mac, vlan = mac_entry ip = None fqdn = None mac_vendor = None if mac and mac in arp_lookup.keys(): for entry in arp_lookup[mac]: ip, arp_vlan = entry if vlan == arp_vlan: if mac and mac_lookup: mac_vendor = mac_to_vendor(mac) if dns_lookup and ip: try: fqdn, _, _, = socket.gethostbyaddr(ip) except socket.herror: pass output_line = [intf, state, mac, mac_vendor, fqdn, ip, vlan, desc] output.append(output_line) else: output_line = [intf, state, mac, mac_vendor, fqdn, ip, vlan, desc] output.append(output_line) else: output_line = [intf, state, None, None, None, None, None, desc] output.append(output_line) output.sort(key=lambda x: utilities.human_sort_key(x[0])) output.insert(0, ["Interface", "Status", "MAC", "MAC Vendor", "DNS Name", "IP Address", "VLAN", "Description"]) output_filename = session.create_output_filename("PortMap", ext=".csv") utilities.list_of_lists_to_csv(output, output_filename) # Return terminal parameters back to the original state. session.end_cisco_session()
def get_wlan_detail(session, to_cvs=False): """ A function that captures the WLC AireOS wlan & remote-lan & guest-lan details and returns an output list :param session: The script object that represents this script being executed :type session: session.Session :return: A list of wlan details :rtype: list of lists """ # Get the show wlan summary send_cmd = "show wlan summary" raw_wlan_summary = session.get_command_output(send_cmd) # Get the show remote-lan summary send_cmd = "show remote-lan summary" raw_rlan_summary = session.get_command_output(send_cmd) # Get the show guest-lan summary send_cmd = "show guest-lan summary" raw_glan_summary = session.get_command_output(send_cmd) template_file = session.script.get_template( "cisco_aireos_show_wlan_summary.template") wlan_summary_dict = utilities.textfsm_parse_to_dict( raw_wlan_summary, template_file) rlan_summary_dict = utilities.textfsm_parse_to_dict( raw_rlan_summary, template_file) glan_summary_dict = utilities.textfsm_parse_to_dict( raw_glan_summary, template_file) output_raw = '' output_list = [] for wlan_entry in wlan_summary_dict: send_cmd = "show wlan " + format(wlan_entry["WLAN_Identifier"]) output_list.append(session.get_command_output(send_cmd)) raw_rlan_detail = '' for wlan_entry in rlan_summary_dict: send_cmd = "show remote-lan " + format(wlan_entry["WLAN_Identifier"]) output_list.append(session.get_command_output(send_cmd)) raw_glan_detail = '' for wlan_entry in glan_summary_dict: send_cmd = "show guest-lan " + format(wlan_entry["WLAN_Identifier"]) output_list.append(session.get_command_output(send_cmd)) output = [] first = True for output_raw in output_list: # TextFSM template for parsing "show wlan <WLAN-ID>" output template_file = session.script.get_template( "cisco_aireos_show_wlan_detail.template") if first: output = utilities.textfsm_parse_to_list(output_raw, template_file, add_header=True) first = False else: output.append( utilities.textfsm_parse_to_list(output_raw, template_file, add_header=False)[0]) if to_cvs: output_filename = session.create_output_filename("wlan-detail", ext=".csv") utilities.list_of_lists_to_csv(output, output_filename) return output
def script_main(session): supported_os = ["IOS", "NXOS"] if session.os not in supported_os: logger.debug("Unsupported OS: {0}. Exiting program.".format(session.os)) session.message_box("{0} is not a supported OS for this script.".format(session.os), "Unsupported OS", options=sessions.ICON_STOP) return int_table = get_int_status(session) mac_table = get_mac_table(session) desc_table = get_desc_table(session) arp_lookup = get_arp_info(session) output = [] for intf_entry in int_table: intf = intf_entry[0] # Exclude VLAN interfaces if intf.lower().startswith("v"): continue state = intf_entry[2] # Get interface description, if one exists desc = None if intf in desc_table.keys(): desc = desc_table[intf] # Record upsteam information for routed ports if intf_entry[3] == 'routed': vlan = intf_entry[3] mac = None ip = None fqdn = None mac_vendor = None if intf in arp_lookup.keys(): arp_list = arp_lookup[intf] for entry in arp_list: mac, ip = entry if mac: mac_vendor = mac_to_vendor(mac) if dns_lookup and ip: try: fqdn, _, _, = socket.gethostbyaddr(ip) except socket.herror: pass output_line = [intf, state, mac, mac_vendor, fqdn, ip, vlan, desc] output.append(output_line) else: output_line = [intf, state, mac, mac_vendor, fqdn, ip, vlan, desc] output.append(output_line) # Record all information for L2 ports elif intf in mac_table.keys(): for mac_entry in mac_table[intf]: mac, vlan = mac_entry ip = None fqdn = None mac_vendor = None if mac and mac in arp_lookup.keys(): for entry in arp_lookup[mac]: ip, arp_vlan = entry if vlan == arp_vlan: if mac: mac_vendor = mac_to_vendor(mac) if dns_lookup and ip: try: fqdn, _, _, = socket.gethostbyaddr(ip) except socket.herror: pass output_line = [intf, state, mac, mac_vendor, fqdn, ip, vlan, desc] output.append(output_line) else: output_line = [intf, state, mac, mac_vendor, fqdn, ip, vlan, desc] output.append(output_line) else: output_line = [intf, state, None, None, None, None, None, desc] output.append(output_line) output.sort(key=lambda x: utils.human_sort_key(x[0])) output.insert(0, ["Interface", "Status", "MAC", "MAC Vendor", "DNS Name", "IP Address", "VLAN", "Description"]) output_filename = session.create_output_filename("PortMap", ext=".csv") utils.list_of_lists_to_csv(output, output_filename) # Clean up before closing session session.end()
def script_main(session, ask_vrf=True, vrf=None): """ | SINGLE device script | Author: Jamie Caesar | Email: [email protected] This script will grab the EIGRP topology from a Cisco IOS or NXOS device and export a summary of how many networks are learned from each successor/feasible successor and output it into a CSV file. It will also give a detailed breakdown of every network that was learned from a particular successor :param session: A subclass of the sessions.Session object that represents this particular script session (either SecureCRTSession or DirectSession) :type session: sessions.Session :param ask_vrf: A boolean that specifies if we should prompt for which VRF. The default is true, but when this module is called from other scripts, we may want avoid prompting and supply the VRF with the "vrf" input. :type ask_vrf: bool :param vrf: The VRF that we should get the route table from. This is used only when ask_vrf is False. :type vrf: str """ # Get script object that owns this session, so we can check settings, get textfsm templates, etc script = session.script # Start session with device, i.e. modify term parameters for better interaction (assuming already connected) session.start_cisco_session() # Validate device is running a supported OS session.validate_os(["IOS", "NXOS"]) # If we should prompt for a VRF, then do so. Otherwise use the VRF passed into the function (if any) if ask_vrf: selected_vrf = script.prompt_window("Enter the VRF name. (Leave blank for default VRF, 'all' for all VRFs)") selected_vrf = selected_vrf.strip() logger.debug("Input VRF: {0}".format(selected_vrf)) else: selected_vrf = vrf logger.debug("Received VRF: {0}".format(selected_vrf)) # If we have a VRF, modify our commands and hostname to reflect it. If not, pull the default route table. if selected_vrf: if session.os == "IOS": if selected_vrf == "all": send_cmd = "show ip eigrp vrf * topology" else: send_cmd = "show ip eigrp vrf {0} topology".format(selected_vrf) else: if selected_vrf == "*": send_cmd = "show ip eigrp topology vrf all" else: send_cmd = "show ip eigrp topology vrf {0}".format(selected_vrf) else: send_cmd = "show ip eigrp topology" logger.debug("Generated Command: {0}".format(send_cmd)) raw_topo = session.get_command_output(send_cmd) if session.os == "IOS": template_file = script.get_template("cisco_ios_show_ip_eigrp_topology.template") else: template_file = script.get_template("cisco_nxos_show_ip_eigrp_topology.template") fsm_results = utilities.textfsm_parse_to_dict(raw_topo, template_file) detailed_results = process_topology(fsm_results) for process, nexthops in detailed_results.iteritems(): nexthop_list = sorted(nexthops.keys(), key=utilities.human_sort_key) vrf = process[0] as_num = process[1] rid = process[2] output = [["Hostname:", session.hostname], ["VRF:", vrf], ["AS:", as_num], ["Router ID:", rid], ["", ""], ["Nexthop", "Routes Learned"]] # output.append(["EIGRP TOPOLOGY SUMMARY", ""]) for nexthop in nexthop_list: output.append([nexthop, len(nexthops[nexthop])]) output.append(["", ""]) # output.append(["DETAILED ROUTE LIST",""]) for nexthop in nexthop_list: output.append(["Nexthop", "Routes"]) sorted_networks = sorted(nexthops[nexthop], key=utilities.human_sort_key) for network in sorted_networks: output.append([nexthop, network]) output.append(["",""]) if vrf: output_filename = session.create_output_filename("{0}-eigrp-{1}-summary".format(vrf, as_num), ext=".csv") else: output_filename = session.create_output_filename("-eigrp-{0}-summary".format(as_num), ext=".csv") utilities.list_of_lists_to_csv(output, output_filename) # Return terminal parameters back to the original state. session.end_cisco_session()