Exemple #1
0
    def check_cores(self):
        """Verify if any core on the device.

        Returns:
            Core files name

        Example:
            >>> check_cores()
        """

        cores = []
        # Execute command to check for cores
        header = [
            "VDC", "Module", "Instance", "Process-name", "PID",
            "Date\(Year-Month-Day Time\)"
        ]

        if self.device.alias == 'uut':
            # In case of restarting process on a the main VDC
            output = oper_fill_tabular(device=self.device,
                                       show_command='show cores vdc-all',
                                       header_fields=header,
                                       index=[5])
        else:
            # In case of restarting process on a sub-VDC
            self.device.disconnect()
            output = oper_fill_tabular(device=self.device,
                                       show_command='show cores',
                                       header_fields=header,
                                       index=[5])

        if not output.entries:
            log.info('No core found')
            return []

        # Parse through output to collect core information (if any)
        for k in sorted(output.entries.keys(), reverse=True):
            row = output.entries[k]
            date = row.get("Date\(Year-Month-Day Time\)", None)
            if not date:
                continue
            date_ = datetime.strptime(date, '%Y-%m-%d %H:%M:%S')

            # Save core info
            core_info = dict(module=row['Module'],
                             pid=row['PID'],
                             instance=row['Instance'],
                             process=row['Process-name'],
                             date=date.replace(" ", "_"))
            cores.append(core_info)

        return cores
 def cli(self, output=None):
     parsed_dict = {}
     if output is None:
         out = self.device.execute(self.cli_command)
     else:
         out = output
     # REBOOT DATE TIME           REBOOT REASON
     # -------------------------------------------------------------------------
     # 2020-06-04T04:54:36+00:00  Initiated by user
     # 2020-06-16T09:19:57+00:00  Initiated by user
     # 2020-06-18T13:28:53+00:00  Initiated by user - activate 99.99.999-4542
     # 2020-06-18T13:46:43+00:00  Software initiated - activate 99.99.999-4499
     # 2020-06-18T14:03:24+00:00  Initiated by user - activate 99.99.999-4542
     # 2020-06-18T14:20:11+00:00  Software initiated - activate 99.99.999-4499
     # 2020-07-06T08:49:18+00:00  Initiated by user - activate 99.99.999-4567
     if out:
         out = pg.oper_fill_tabular(
             device_output=out,
             header_fields=["REBOOT DATE TIME", "REBOOT REASON"],
             index=[0])
         return_dict = out.entries
         reboot_date_time = {}
         for keys in return_dict.keys():
             dict1 = {}
             dict1['reboot_reason'] = return_dict[keys]['REBOOT REASON']
             reboot_date_time[keys] = dict1
         parsed_dict['reboot_date_time'] = reboot_date_time
     return parsed_dict
Exemple #3
0
    def cli(self, output=None):
        if output is None:
            out = self.device.execute(self.cli_command)
        else:
            out = output

        # Interface                Name                     Security
        # GigabitEthernet0/0       outside                    0
        header = ['Interface', 'Name', 'Security']

        result = parsergen.oper_fill_tabular(
            device_output=out,
            device_os='asa',
            header_fields=header,
            index=[0]
        )
        nameif_entries = result.entries

        line_dict = {}

        for k in nameif_entries.keys():
            curr_dict = nameif_entries[k]

            interface_dict = line_dict.setdefault(k, {})
            interface_dict.update({'interface': curr_dict['Interface']})
            interface_dict.update({'name': curr_dict['Name']})
            interface_dict.update({
                'security_level': int(curr_dict['Security'])
            })

        return line_dict
    def cli(self, output=None):
        if output is None:
            output = self.device.execute(self.cli_command)
        
        #Subscription ID  Msgs Sent  Msgs Drop  Records Sent Connection Info
        #---------------- ---------- ---------- ------------ -----------------------------------------
        #2147483648       246        0          126690       admin
        header = ["Subscription ID", "Msgs Sent", "Msgs Drop", "Records Sent", "Connection Info"]
        label_fields = ['sub_id', 'msg_sent', 'msg_drop', 'record_sent', 'connection_info']

        ret_dict = dict()
        if output:
            tmp_dict = parsergen.oper_fill_tabular(device_output=output, device_os='iosxe', header_fields=header,
                    label_fields=label_fields, index=[0]).entries

            for k in tmp_dict:
                del tmp_dict[k]["sub_id"]
                ret_dict[int(k)] = tmp_dict[k]

                ret_dict[int(k)]["msg_sent"] = int(ret_dict[int(k)]["msg_sent"])
                ret_dict[int(k)]["msg_drop"] = int(ret_dict[int(k)]["msg_drop"])
                ret_dict[int(k)]["record_sent"] = int(ret_dict[int(k)]["record_sent"])
            ret_dict = {"sub_id": ret_dict}

        return ret_dict
    def cli(self, con_idx=None, output=None):
        if output is None:
            if con_idx:
                cmd = self.cli_command[1].format(con_idx=con_idx)
            else:
                cmd = self.cli_command[0]
            output = self.device.execute(cmd)

        ret_dict = dict()

        if output:
            #Index Peer Address               Port  VRF Source Address             State      State Description
            #----- -------------------------- ----- --- -------------------------- ---------- --------------------
            #    0 5.40.26.169                49066 0   0.0.0.0                    Active     Connection created for protocol netconf
            # or
            #Index Peer Address               Port  VRF Source Address             State      State Description
            #----- -------------------------- ----- --- -------------------------- ---------- --------------------
            #    0 5.40.26.169                49066 0 M 0.0.0.0                    Active     Connection created for protocol netconf
            header = ["Index", "Peer Address", "Port", "VRF", "Source Address", "State", "State Description"]
            label_fields = ["index", "peer_address", "port", "vrf", "source_address", "state", "state_description"]

            tmp_dict = parsergen.oper_fill_tabular(device_output=output, device_os='iosxe', header_fields=header,
                    label_fields=label_fields, index=[0]).entries

            for k in tmp_dict:
                del tmp_dict[k]["index"]
                ret_dict[int(k)] = tmp_dict[k]

                ret_dict[int(k)]["port"] = int(ret_dict[int(k)]["port"])
                ret_dict[int(k)]["vrf"] = int(re.sub('M', '', ret_dict[int(k)]["vrf"]))

            ret_dict = {"index": ret_dict}

        return ret_dict
Exemple #6
0
 def cli(self, output=None):
     parsed_dict = {}
     if output is None:
         out = self.device.execute(self.cli_command)
     else:
         out = output
     # VERSION         ACTIVE  DEFAULT  PREVIOUS  CONFIRMED  TIMESTAMP
     # ---------------------------------------------------------------------------------
     # 99.99.999-4499  false   false    true      -          2020-06-01T03:30:46-00:00
     # 99.99.999-4542  false   false    false     -          2020-06-18T06:30:30-00:00
     # 99.99.999-4567  true    true     false     auto       2020-07-06T01:51:18-00:00
     if out:
         out = pg.oper_fill_tabular(device_output=out,
                                    header_fields=[
                                        "VERSION", "ACTIVE", "DEFAULT",
                                        "PREVIOUS", "CONFIRMED", "TIMESTAMP"
                                    ],
                                    label_fields=[
                                        "version", "active", "default",
                                        "previous", "confirmed", "timestamp"
                                    ],
                                    index=[0])
         return_dict = out.entries
         version_dict = {}
         for keys in return_dict.keys():
             dict1 = {}
             del return_dict[keys]['version']
             version_dict[keys] = return_dict[keys]
         parsed_dict['version'] = version_dict
     return parsed_dict
Exemple #7
0
def get_arps(dev):
    """Retrieve the ARP entries from the device.
       ** As written only supports NX-OS devices.
    """
    # Output from NX-OS Device
    # Flags: * - Adjacencies learnt on non-active FHRP router
    #        + - Adjacencies synced via CFSoE
    #        # - Adjacencies Throttled for Glean
    #        CP - Added via L2RIB, Control plane Adjacencies
    #        PS - Added via L2RIB, Peer Sync
    #        RO - Re-Originated Peer Sync Entry
    #        D - Static Adjacencies attached to down interface
    #
    # IP ARP Table for all contexts
    # Total number of entries: 1
    # Address         Age       MAC Address     Interface       Flags
    # 10.0.2.2        00:04:55  5254.0012.3502  mgmt0

    abstract = genie_prep(dev)

    nxos_arp_command = "show ip arp vrf all"

    arps = parsergen.oper_fill_tabular(
        device=dev,
        show_command=nxos_arp_command,
        header_fields=["Address", "Age", "MAC Address", "Interface", "Flags"],
    )

    return arps.entries
Exemple #8
0
def check_cores(device, core_list, **kwargs):

    # Init
    status = OK

    # Check if device is VDC
    try:
        output = device.parse('show vdc current-vdc')
    except Exception as e:
        logger.warning(e)
        meta_info = "Unable to execute 'show vdc current-vdc' to check if device is VDC"
        logger.error(meta_info)
        status = ERRORED(meta_info)
        return status

    # Check if device is VDC
    if 'current_vdc' in output and output['current_vdc']['id'] != '1':
        cmd = 'show cores'
    else:
        cmd = 'show cores vdc-all'

    # Execute command to check for cores
    header = [
        "VDC", "Module", "Instance", "Process\-name", "PID",
        "Date\(Year\-Month\-Day Time\)"
    ]
    output = oper_fill_tabular(device=device,
                               show_command=cmd,
                               header_fields=header,
                               index=[5])

    if not output.entries:
        meta_info = "No cores found!"
        logger.info(meta_info)
        return OK(meta_info)

    # Parse through output to collect core information (if any)
    for k in sorted(output.entries.keys(), reverse=True):
        row = output.entries[k]
        date = row.get("Date\\(Year\\-Month\\-Day Time\\)", None)
        if not date:
            continue
        date_ = datetime.strptime(date, '%Y-%m-%d %H:%M:%S')

        # Save core info
        core_info = dict(module=row['Module'],
                         pid=row['PID'],
                         instance=row['Instance'],
                         process=row['Process\\-name'],
                         date=date.replace(" ", "_"))
        core_list.append(core_info)

        meta_info = "Core dump generated for process '{}' at {}".\
            format(row['Process\\-name'], date_)
        logger.error(meta_info)
        status += CRITICAL(meta_info)

    return status
Exemple #9
0
    def pythonTabularParsing(self, uut, show_arp_header_fields,
                             show_arp_table_title_pattern,
                             show_arp_table_parse_index):
        """ Native Python Parsing of tabular CLI output"""

        res = pg.oper_fill_tabular(device=uut,
                                    show_command="SHOW_ARP",
                                    refresh_cache=True,
                                    header_fields=show_arp_header_fields,
                                    index = show_arp_table_parse_index,
                                    table_title_pattern = \
                                        show_arp_table_title_pattern)
        log.info("Tabular parse result:\n" + pprint.pformat(res.entries))
Exemple #10
0
    def cli(self, vni=None, output=None):

        if output is None:
            cmd = self.cli_command[0]
            if vni:
                cmd = self.cli_command[1].format(vni=vni)
            output = self.device.execute(cmd)

        parsed_dict_vlan = oper_fill_tabular(header_fields=[
            "Interface", "VNI", "Multicast-group", "VNI state", "Mode", "VLAN",
            "cfg", "vrf"
        ],
                                             label_fields=[
                                                 'interface', 'vni', 'mcast',
                                                 'vni_state', 'mode', 'vlan',
                                                 'cfg', 'vrf'
                                             ],
                                             index=[0, 1],
                                             device_output=output,
                                             device_os='iosxe').entries

        if parsed_dict_vlan:
            return parsed_dict_vlan

        parsed_dict_bd = oper_fill_tabular(header_fields=[
            "Interface", "VNI", "Multicast-group", "VNI state", "Mode", "BD",
            "cfg", "vrf"
        ],
                                           label_fields=[
                                               'interface', 'vni', 'mcast',
                                               'vni_state', 'mode', 'bd',
                                               'cfg', 'vrf'
                                           ],
                                           index=[0, 1],
                                           device_output=output,
                                           device_os='iosxe').entries

        return parsed_dict_bd
Exemple #11
0
    def cli(self, output=None):
        if output is None:
            out = self.device.execute(self.cli_command)
        else:
            out = output

        if not 'Flags' not in out:
            header = ['Address', 'Age', 'MAC Address', 'Interface']
        else:
            header = ['Address', 'Age', 'MAC Address', 'Interface', 'Flags']
        result = parsergen.oper_fill_tabular(device_output=out,
                                             device_os='nxos',
                                             header_fields=header,
                                             index=[0])
        return result.entries
Exemple #12
0
 def test(self, steps):
     for device_name, device in self.execute_platform.items():
         header=['flow_type','priority','sw_police_id','hw_policer_addr',
              'Cur. Rate','burst','static_avgrate','avgrate_type',
                   'AggrAccepts','AggrDrops','TOS Value']
         output = self.execute_platform[device_name]
         result = parsergen.oper_fill_tabular(device_output=output, device_os='iosxr', header_fields=header, index=[0])
         output = result.entries
         logger.info(f"Structured Output from SHOW LPTS POLICER \n {output} ")
         police_drops = Dq(output).value_operator('AggrDrops', '>', 0).reconstruct()
         if police_drops == {}:
             self.passed(f"No issues found with drops on the lpts Policer")
         
         else: 
             self.failed(f'Drops found on the control plane policer on the following processes:\n {police_drops.keys()}')
    def cli(self,output=None):
        if output is None:
            out = self.device.execute(self.cli_command)
        else:
            out = output
        
        #Removing unneccessary header
        try:
            strout= re.findall(r'\s+[DST PUBLIC \s]+RX+\s+TX+\s',out)
            out=out.replace(strout[0],"")
        except:
            out=out


        #parsed output using parsergen
        parsed_out = pg.oper_fill_tabular(device_output=out,  
                                    header_fields=["SYSTEM IP", "SITE ID", "COLOR", "STATE", "IP", "PORT", "ENCAP","TIME","PKTS","PKTS","DEL"],
                                    label_fields=["system_ip", "site_id", "color", "state", "dst_public_ip", "dst_public_port","encap","time","rx_pkts","tx_pkts","del"], 
                                    index= [1,0,4,7]
                                    )

        #creating a parsed dict using the output
        parsed_dict = parsed_out.entries

        #Parsing the dict according to the schema
        out_dict={}
        out_dict['site_id']={}
        cur_dict=out_dict['site_id']



        for key in parsed_dict.keys():
            cur_dict[key]={}
            cur_dict[key]['system_ip']={}
            for subkey in parsed_dict[key].keys():
                cur_dict[key]['system_ip'][subkey]={}
                cur_dict[key]['system_ip'][subkey]['dst_public_ip']={}
                for subsubkey in parsed_dict[key][subkey].keys():
                    cur_dict[key]['system_ip'][subkey]['dst_public_ip'][subsubkey]={}
                    cur_dict[key]['system_ip'][subkey]['dst_public_ip'][subsubkey]['time']={}
                    for subsubsubkey in parsed_dict[key][subkey][subsubkey].keys():
                        cur_dict[key]['system_ip'][subkey]['dst_public_ip'][subsubkey]['time'][subsubsubkey]={}
                        for valuekey in parsed_dict[key][subkey][subsubkey][subsubsubkey].keys():
                            if valuekey not in ['site_id','system_ip','dst_public_ip','time']:
                                cur_dict[key]['system_ip'][subkey]['dst_public_ip'][subsubkey]['time'][subsubsubkey][valuekey]=parsed_dict[key][subkey][subsubkey][subsubsubkey][valuekey]


        return out_dict
    def cli(self):
        # excute command to get output
        cmd = 'show nve peers'
        output = self.device.execute(cmd)

        header = [
            'Interface', 'VNI', 'Type', 'Peer-IP', 'Router-RMAC', 'eVNI',
            'state', 'flags', 'UP time'
        ]

        result = parsergen.oper_fill_tabular(device_output=output,
                                             device_os='iosxe',
                                             header_fields=header,
                                             index=[0])

        return result.entries
Exemple #15
0
def runGenieParser(content, columnheaders, index):
    # example columnheaders =  ["Protocol", "Address", "Age (min)", "Hardware", "Addr", "Type", "Interface"]

    try:
        genie_resObj = parsergen.oper_fill_tabular(
            device_output=str(content),
            table_terminal_pattern=r"^\n",
            header_fields=columnheaders,
            index=index)
    except:
        # old python method, still works in Python 3 print('Error:', sys.exc_info()[1])
        print('Error:', sys.exc_info()[1])

    result = genie_resObj.entries
    resulttxt = json.dumps(result, indent=2)
    return resulttxt
Exemple #16
0
def get_ospf_neighState(index_value, field, index=0):
    tb = load(
        '/home/dsalva/PycharmProjects/mse-cisco-R/mse-cisco/Resources/Source/InputFiles/testbed.yaml'
    )
    dev = tb.devices['Automation-ASR9K-PE2']
    dev.connect()
    output = dev.device.execute('show ospf neighbor')
    header = [
        'Neighbor ID', 'Pri', 'State', 'Dead Time', 'Address', 'Interface'
    ]
    result = oper_fill_tabular(device_output=output,
                               device_os='iosxr',
                               header_fields=header,
                               index=index)
    state = result.entries[index_value][field]
    dev.disconnect()
    return state
    def cli(self, output=None):
        if output is None:
            output = self.device.execute(self.cli_command)

        ret_dict = dict()
        if output:
            header = ["Name", "Type", "Profile", "State", "Explanation"]
            label_fields = [i.lower() for i in header]

            ret_dict = parsergen.oper_fill_tabular(device_output=output, device_os='iosxe', header_fields=header, 
                    label_fields=label_fields, index=[0]).entries

            for k in ret_dict:
                del ret_dict[k]["name"]

            ret_dict = {"name": ret_dict}
        return ret_dict
Exemple #18
0
def parse_cli(device):
    # By the default it will take cli
    output = device.execute('show interface brief')
    result = parsergen.oper_fill_tabular(
        device_output=output,
        device_os='nxos',
        header_fields=[[
            'Ethernet', 'VLAN', 'Type', 'Mode', 'Status', 'Reason', 'Speed',
            'Port'
        ], ['Interface', '', '', '', '', '', '', 'Ch \#']],
        label_fields=[
            'Ethernet Interface', 'VLAN', 'Type', 'Mode', 'Status', 'Reason',
            'Speed', 'Port'
        ],
        index=[0])

    return result
    def _nve_parse(self):
        output = self.device.execute('show nve vni')

        # Create list of Header names of the table from show nve nvi - must match exactly to that which is output on cli
        header = [
            'Interface', 'VNI', 'Multicast-group', 'VNI state', 'Mode', 'BD',
            'cfg', 'vrf'
        ]

        # Use Parsergen to parse the output and create structured output (dictionary of operational stats)
        result = parsergen.oper_fill_tabular(device_output=output,
                                             device_os='iosxe',
                                             header_fields=header,
                                             index=[0])

        intlist = [x for x in result.entries]

        return intlist
Exemple #20
0
def show_ip_eigrp_neighbors(uut):
    """
    Parsing show ip eigrp neigbors using parsergen

    sample output
    EIGRP-IPv4 Neighbors for AS(100)
    H   Address                 Interface              Hold Uptime   SRTT   RTO  Q  Seq
                                                       (sec)         (ms)       Cnt Num
    1   10.1.1.3                Tu1                      10 02:51:11   26   156  0  3
    0   10.1.1.4                Tu1                      12 02:51:12    5   100  0  4

    """ # noqa
    # Use connect method to initiate connection to the device under test
    if not uut.is_connected():
        uut.connect()

    # collect show command output
    command = 'show ip eigrp neighbors'
    output = uut.execute(command)

    try:
        headers = [
            "H", "Address", "Interface", "Hold", "Uptime", "SRTT", "RTO",
            " Q ", "Seq"
        ]

        label_fields = [
            "H", "Address", "Interface", "Uptime", "SRTT", "RTO", "QCnt",
            "SeqNum"
        ]

        eigrp_dict = parsergen.oper_fill_tabular(device_output=output,
                                                 device_os='iosxe',
                                                 header_fields=headers,
                                                 label_fields=label_fields,
                                                 index=[1])
        if '' in eigrp_dict.entries:
            del eigrp_dict.entries['']

        return eigrp_dict.entries

    except Exception as e:
        pass
    def cli(self, interface=None):
        # run the command to obtain the TEXT output so that we can then run it
        # through the parsergen.  We do this because if the caller does not
        # provide an interface, or the provided interface is a range, we will
        # need to parse the same output multiple times; once for each interface
        # found in the output.

        cli_cmd = (self.cli_command[0] if not interface else
                   self.cli_command[1].format(interface=interface))

        oper_res = pg.oper_fill_tabular(device=self.device,
                                        show_command=cli_cmd,
                                        header_fields=self.OPER_TABLE_HEADERS,
                                        label_fields=self.OPER_TABLE_LABLES)

        # declare a dict variable that must returned from this method, and will
        # need to conform to the schema definition.

        schema_output = dict()

        if_names = list(oper_res.entries)
        if not if_names:
            return schema_output

        # perform second command to get the inventory CLI output, and then
        # parse for each interface name found from the first table parse.

        cli_inventory = self.device.execute("show inventory")
        for if_name in if_names:
            schema_output[if_name] = if_schema_data = {}

            data = parse_inventory_for_interface(if_name, cli_inventory)
            if not data:
                continue

            if_schema_data['type'] = data[f'{MARKUP_PREFIX}.type']
            # vendor is not supported on this platform?
            if_schema_data['part_number'] = data[
                f'{MARKUP_PREFIX}.part_number']
            if_schema_data['serial_number'] = data[
                f'{MARKUP_PREFIX}.serial_number']

        return schema_output
 def cli(self, output=None):
     parsed_dict = {}
     if output is None:
         out = self.device.execute(self.cli_command)
     else:
         out = output
     # App id                                   State
     # ---------------------------------------------------------
     # utd                                      RUNNING
     if out:
         out = pg.oper_fill_tabular(device_output=out,
                                    header_fields=["App id", "State"],
                                    index=[0])
         return_dict = out.entries
         app_id = {}
         for keys in return_dict.keys():
             app_dict = {}
             app_dict['state'] = return_dict[keys]['State']
             app_id[keys] = app_dict
         parsed_dict['app_id'] = app_id
     return parsed_dict
Exemple #23
0
    def runGenieParser(self):

        content = self.teSource.toPlainText()
        cheaders = self.teTemplate.toPlainText()
        keystring = self.lineEdit.text()
        columnheaders = str(cheaders).split("\n")
        # columnheaders =  ['Device ID', 'Local Intrfce', 'Holdtme', 'Capability', 'Platform', 'Port ID']

        try:
            keys = int(keystring)
            res = parsergen.oper_fill_tabular(device_output=str(content),
                                              table_terminal_pattern=r"^\n",
                                              header_fields=columnheaders,
                                              index=keys)
        except:
            # old python method, still works in Python 3 print('Error:', sys.exc_info()[1])
            print('Error:', sys.exc_info()[1])

        result = res.entries
        resulttxt = json.dumps(result, indent=2)
        self.teResult.setPlainText(resulttxt)
Exemple #24
0
    def _parse_generic_tabular(cli_output, os, headers, key_index):
        # Boilerplate code to get the parser functional
        tb = Testbed()
        device = Device("new_device", os=os)

        device.custom.setdefault("abstraction", {})["order"] = ["os"]
        device.cli = AttrDict({"execute": None})

        # Do the parsing
        # result = parsergen.oper_fill_tabular(device_output=cli_output, device_os=nos, header_
        # fields=headers, index=[key])
        result = parsergen.oper_fill_tabular(device_output=cli_output,
                                             device_os=os,
                                             header_fields=headers,
                                             index=key_index)

        # Structured data, but it has a blank entry because of the first line of the output
        # being blank under the headers.
        parsed_output = result.entries

        return parsed_output
    def cli(self):
        # excute command to get output
        cmd = 'show nve vni'

        output = self.device.execute(cmd)

        header = [
            'Interface', 'VNI', 'Multicast-group', 'VNI state', 'Mode', 'BD',
            'cfg', 'vrf'
        ]
        label = [
            'Interface', 'VNI', 'Multicast-group', 'VNIstate', 'Mode', 'BD',
            'cfg', 'vrf'
        ]

        result = parsergen.oper_fill_tabular(device_output=output,
                                             device_os='iosxe',
                                             header_fields=header,
                                             label_fields=label,
                                             index=[0])

        return result.entries
    def test(self, steps):

        print(path_store)
        for device_name, device in self.execute_cpu.items():
            header = ['PID', '1Min', '5Min', '15Min', 'Process']
            output = self.execute_cpu[device_name]
            output = re.sub('%', ' ', output)
            result = parsergen.oper_fill_tabular(device_output=output,
                                                 device_os='iosxr',
                                                 header_fields=header,
                                                 index=[0])
            output = result.entries
            cpu_bad = Dq(output).value_operator('5Min', '>=', 75).reconstruct()
            process_id = str(cpu_bad.keys())
            if cpu_bad != {}:
                self.failed(
                    f'Very High 5 Minute CPU detected on {device} with the following Process ID {process_id}'
                )

            else:
                self.passed(
                    f'No issues found with the CPU Utilisation on {device_name}'
                )
Exemple #27
0
__license__ = "Cisco Sample Code License, Version 1.0"



#Import Genie libraries
from genie.conf import Genie
from genie import parsergen
import re

from pprint import pprint

#Create Testbed Object with Genie
testbed = Genie.init('vagrant_multi_ios.yaml')

#Create Device Object
uut = testbed.devices.iosxe1

#Use connect method to initiate connection to the device under test
uut.connect()

#Execute command show nve nvi on connected device
output = uut.device.execute('show nve vni')

#Create list of Header names of the table from show nve nvi - must match exactly to that which is output on cli
header = ['Interface', 'VNI', 'Multicast-group', 'VNI state', 'Mode', 'BD', 'cfg', 'vrf']

#Use Parsergen to parse the output and create structured output (dictionary of operational stats)
result = parsergen.oper_fill_tabular(device_output=output, device_os='iosxe', header_fields=header, index=[0])

#Pretty Print the Dictionary
pprint(result.entries)
Exemple #28
0
from genie import testbed
from genie import parsergen
import pprint

#load testbed file
testbed = testbed.load('tbed2.yml')
#choose IOS device and connect
device = testbed.devices['R2']
device.connect()

#Execute show interface summary command
output = device.execute('show interface summary')

# Parse tabular data
result = parsergen.oper_fill_tabular(header_fields=[
    "Interface", "IHQ", "IQD", "OHQ", "OQD", "RXBS", "RXPS", "TXBS", "TXPS",
    "TRTL"
],
                                     label_fields=[
                                         "INTERFACE", "IHQ", "IQD", "OHQ",
                                         "OQD", "RXBS", "RXPS", "TXBS", "TXPS",
                                         "TRTL"
                                     ],
                                     index=[0],
                                     delimiter="*",
                                     device_output=output,
                                     device_os='ios')

#Print the result
pprint.pprint(result.entries)
Exemple #29
0
    def cli(self):
        """parsing mechanism: cli

        Function cli() defines the cli type output parsing mechanism which consists of the 3 steps:
        execution, transforming, returning
        """

        parsed_dict = {}
        cmd = 'show ip sla summary'

        out = self.device.execute(cmd)

        #ID           Type        Destination       Stats       Return      Last
        #                                                       Code        Run
        #-----------------------------------------------------------------------
        #*1           tcp-connect 123.23.213.32     RTT=44      OK          21 seconds ag
        #                                                                   o
        #
        #
        #
        #*2           dns         11.121.2.123      -           Timeout     7 seconds ago

        if out:
            headers = [[
                'ID', 'Type', 'Destination', 'Stats', 'Return', 'Last'
            ], ['', '', '', '', 'Code', 'Run']]
            result = parsergen.oper_fill_tabular(device_output=out,
                                                 header_fields=headers,
                                                 label_fields=[
                                                     'id', 'type',
                                                     'destination',
                                                     'rtt_stats_mseconds',
                                                     'return_code',
                                                     'last_run_seconds_ago'
                                                 ])
            struct_output = result.entries
            if struct_output:
                for id, id_dict in struct_output.items():
                    if id:
                        # Defining patterns to be matched for different columns
                        # The patterns for the state of the ip sla probe defined by the Codes: * active, ^ inactive, ~ pending
                        active_pattern = re.compile(r'\*(\S+)')
                        inactive_pattern = re.compile(r'\^(\S+)')
                        pending_pattern = re.compile(r'\~(\S+)')

                        # The pattern for the last_run_seconds_ago collumn
                        last_run_pattern = re.compile(r'(\S+) sec\S+')

                        # The pattern for the rtt_stats_mseconds (for milliseconds)
                        # The first pattern is for normal RTT denoted in milliseconds and therefore would not require any further processing
                        # The second pattern is for RTT denoted in microseconds and for standardisation purposes will be converted to milliseconds
                        rtt_pattern_milliseconds = re.compile(r'RTT=(\d{1,4})')
                        rtt_pattern_microseconds = re.compile(
                            r'RTT=(\d{1,4})u')

                        # Setting the probe_id and the codes values
                        if active_pattern.match(id):
                            probe_id = active_pattern.match(id).group(1)
                            id_dict['probe_status'] = 'active'
                        elif inactive_pattern.match(id):
                            probe_id = inactive_pattern.match(id).group(1)
                            id_dict['probe_status'] = 'inactive'
                        elif pending_pattern.match(id):
                            probe_id = pending_pattern.match(id).group(1)
                            id_dict['probe_status'] = 'pending'
                        del id_dict['id']

                        # Setting the rtt_stats_mseconds column value
                        # If the value is in milliseconds
                        if rtt_pattern_milliseconds.match(
                                id_dict['rtt_stats_mseconds']):
                            id_dict[
                                'rtt_stats_mseconds'] = rtt_pattern_milliseconds.match(
                                    id_dict['rtt_stats_mseconds']).group(1)
                        # If the value is in microseconds
                        elif rtt_pattern_microseconds.match(
                                id_dict['rtt_stats_mseconds']):
                            id_dict['rtt_stats_mseconds'] = int(
                                rtt_pattern_microseconds.match(
                                    id_dict['rtt_stats_mseconds']).group(
                                        1)) / 1000
                        # If the value is a dash, no further processing is needed
                        else:
                            pass

                        # Setting the value for the last_run_seconds_ago collumn
                        if last_run_pattern.match(
                                id_dict['last_run_seconds_ago']):
                            id_dict[
                                'last_run_seconds_ago'] = last_run_pattern.match(
                                    id_dict['last_run_seconds_ago']).group(1)

                        parsed_dict.setdefault('id',
                                               {}).update({probe_id: id_dict})
                    else:
                        # This else clause is added to mitigate the limitation that sometimes the cli output line for this command
                        # may include just the letter 'o' as it would be cut from the Last Run column due to width limitation.
                        pass

        return parsed_dict
Exemple #30
0
# Create Device Object
uut = testbed.devices['uut']

# Use connect method to initiate connection to the device under test
uut.connect()

# Execute command show nve nvi on connected device

# Create list of Header names of the table from the show_command
# these must match exactly to that which is output on cli
header = ['System ID', 'SNPA', 'Level', 'State', 'Hold Time', 'Interface']

# Capture Before output
before = uut.device.execute('show fabricpath isis adjacency')
before = parsergen.oper_fill_tabular(device_output=before,
                                     device_os='nxos',
                                     header_fields=header,
                                     index=[0])

# Capture after output
after = uut.device.execute('show fabricpath isis adjacency')
after = parsergen.oper_fill_tabular(device_output=after,
                                    device_os='nxos',
                                    header_fields=header,
                                    index=[0])

pprint(after.entries)
exclude = ['Hold Time']
dd = Diff(before.entries, after.entries, exclude=exclude)
dd.findDiff()
print(dd)