コード例 #1
0
    def __eq__(self, others):
        if not isinstance(others, ListVRF):
            raise NotImplementedError

        for vrf in self.vrf_lst:
            if vrf not in others.vrf_lst:
                if verbose_mode(
                    user_value=os.environ.get("NETESTS_VERBOSE", NOT_SET),
                    needed_value=LEVEL2
                ):
                    printline()
                    print(f"{H} The following VRF is not in the list \n {vrf}")
                    print(f"{H} List: \n {others.vrf_lst}")
                return False

        for vrf in others.vrf_lst:
            if vrf not in self.vrf_lst:
                if verbose_mode(
                    user_value=os.environ.get("NETESTS_VERBOSE", NOT_SET),
                    needed_value=LEVEL2
                ):
                    printline()
                    print(f"{H} The following VRF is not in the list \n {vrf}")
                    print(f"{H} List: \n {others.vrf_lst}")
                return False

        return True
コード例 #2
0
def _juniper_bgp_api_converter(hostname: str,
                               cmd_output: dict,
                               options={}) -> BGP:

    bgp_sessions_vrf_lst = ListBGPSessionsVRF(list())

    for k, v in cmd_output.items():
        if not isinstance(v.get('bgp'), dict):
            v['bgp'] = format_xml_output(v.get('bgp'))
        if not isinstance(v.get('rid'), dict):
            v['rid'] = format_xml_output(v.get('rid'))
        if verbose_mode(user_value=os.environ.get('NETESTS_VERBOSE', NOT_SET),
                        needed_value=LEVEL3):
            printline()
            PP.pprint(v)

        bgp_sessions_lst = ListBGPSessions(list())

        if ('bgp' in v.keys() and 'bgp-information' in v.get('bgp').keys()
                and v.get('bgp').get('bgp-information') is not None
                and 'bgp-peer' in v.get('bgp').get('bgp-information').keys()):
            for n in v.get('bgp').get('bgp-information').get('bgp-peer'):
                bgp_sessions_lst.bgp_sessions.append(
                    BGPSession(src_hostname=hostname,
                               peer_ip=n.get('peer-address', NOT_SET),
                               peer_hostname=NOT_SET,
                               remote_as=n.get('peer-as', NOT_SET),
                               state_brief=get_bgp_state_brief(
                                   n.get('peer-state', NOT_SET)),
                               session_state=n.get('peer-state', NOT_SET),
                               state_time=NOT_SET,
                               prefix_received=NOT_SET,
                               options=options))
                as_number = n.get('bgp-option-information').get('local-as')

            router_id = NOT_SET
            if ('rid' in v.keys()
                    and 'instance-information' in v.get('rid').keys()
                    and 'instance-core'
                    in v.get('rid').get('instance-information').keys()):
                router_id = v.get('rid') \
                             .get('instance-information') \
                             .get('instance-core') \
                             .get('router-id')

            bgp_sessions_vrf_lst.bgp_sessions_vrf.append(
                BGPSessionsVRF(vrf_name=k,
                               as_number=as_number,
                               router_id=router_id,
                               bgp_sessions=bgp_sessions_lst))

    bgp = BGP(hostname=hostname, bgp_sessions_vrf_lst=bgp_sessions_vrf_lst)

    if verbose_mode(user_value=os.environ.get('NETESTS_VERBOSE', NOT_SET),
                    needed_value=LEVEL1):
        printline()
        print(f'>>>>> {hostname}')
        PP.pprint(bgp.to_json())

    return bgp
コード例 #3
0
ファイル: facts_nxos.py プロジェクト: mirzawaqasahmed/netests
def _nxos_get_facts_ssh(task, options={}):
    output_dict = dict()
    output = task.run(name=f"{NEXUS_GET_FACTS}",
                      task=netmiko_send_command,
                      command_string=NEXUS_GET_FACTS)
    if verbose_mode(user_value=os.environ.get("NETESTS_VERBOSE", NOT_SET),
                    needed_value=LEVEL2):
        print_result(output)

    if output.result != "":
        output_dict[FACTS_SYS_DICT_KEY] = (json.loads(output.result))

    output = task.run(name=f"{NEXUS_GET_INT}",
                      task=netmiko_send_command,
                      command_string=NEXUS_GET_INT)
    if verbose_mode(user_value=os.environ.get("NETESTS_VERBOSE", NOT_SET),
                    needed_value=LEVEL2):
        print_result(output)

    if output.result != "":
        output_dict[FACTS_INT_DICT_KEY] = (json.loads(output.result))

    output = task.run(name=f"{NEXUS_GET_DOMAIN}",
                      task=netmiko_send_command,
                      command_string=NEXUS_GET_DOMAIN)
    if verbose_mode(user_value=os.environ.get("NETESTS_VERBOSE", NOT_SET),
                    needed_value=LEVEL2):
        print_result(output)

    if output.result != "":
        output_dict[FACTS_DOMAIN_DICT_KEY] = (json.loads(output.result))

    task.host[FACTS_DATA_HOST_KEY] = _nxos_facts_ssh_converter(
        hostname=task.host.name, cmd_output=output_dict, options=options)
コード例 #4
0
def select_host_vars(hostname: str, groups: list, protocol: str):
    if truth_vars_exists() is False:
        if verbose_mode(user_value=os.environ.get("NETESTS_VERBOSE", NOT_SET),
                        needed_value=LEVEL4):
            printline()
            print(f"{HEADER} Truth_vars doesn't exists")
        return {}

    if host_vars_exists(hostname, protocol):
        if verbose_mode(user_value=os.environ.get("NETESTS_VERBOSE", NOT_SET),
                        needed_value=LEVEL4):
            printline()
            print(f"{HEADER} Select hosts variables")

        return open_file(path=f"truth_vars/hosts/{hostname}/{protocol}.yml")

    if group_vars_exists(groups[0], protocol):
        if verbose_mode(user_value=os.environ.get("NETESTS_VERBOSE", NOT_SET),
                        needed_value=LEVEL4):
            printline()
            print(f"{HEADER} Select groups variables")

        return open_file(path=f"truth_vars/groups/{groups[0]}/{protocol}.yml")

    if all_vars_exists(protocol):
        if verbose_mode(user_value=os.environ.get("NETESTS_VERBOSE", NOT_SET),
                        needed_value=LEVEL4):
            printline()
            print(f"{HEADER} Select all variables")

        return open_file(path=f"truth_vars/all/{protocol}.yml")
コード例 #5
0
def _cumulus_vrf_api_converter(hostname: str(), cmd_output) -> ListVRF:
    template = open(
        f"{TEXTFSM_PATH}cumulus_net_show_vrf.textfsm"
    )
    results_template = textfsm.TextFSM(template)
    parsed_results = results_template.ParseText(cmd_output.decode())

    list_vrf = ListVRF(list())

    if verbose_mode(
        user_value=os.environ.get("NETESTS_VERBOSE", NOT_SET),
        needed_value=LEVEL3
    ):
        printline()
        print(parsed_results)

    for line in parsed_results:
        vrf = VRF(
            vrf_name=line[0],
            vrf_id=line[1]
        )

        list_vrf.vrf_lst.append(vrf)

    if verbose_mode(
        user_value=os.environ.get("NETESTS_VERBOSE", NOT_SET),
        needed_value=LEVEL1
    ):
        printline()
        print(list_vrf)

    return list_vrf
コード例 #6
0
ファイル: bgp_arista.py プロジェクト: mirzawaqasahmed/netests
def _arista_get_bgp_ssh(task, options={}):
    output_dict = dict()
    output = task.run(
        name=f"{ARISTA_GET_BGP}",
        task=netmiko_send_command,
        command_string=ARISTA_GET_BGP,
    )
    if verbose_mode(user_value=os.environ.get("NETESTS_VERBOSE", NOT_SET),
                    needed_value=LEVEL2):
        print_result(output)

    output_dict['default'] = output.result

    for vrf in task.host[VRF_NAME_DATA_KEY].keys():
        if vrf not in VRF_DEFAULT_RT_LST:
            output = task.run(
                name=ARISTA_GET_BGP_VRF.format(vrf),
                task=netmiko_send_command,
                command_string=ARISTA_GET_BGP_VRF.format(vrf),
            )
            if verbose_mode(user_value=os.environ.get("NETESTS_VERBOSE",
                                                      NOT_SET),
                            needed_value=LEVEL2):
                print_result(output)

            output_dict[vrf] = output.result

    task.host[BGP_SESSIONS_HOST_KEY] = _arista_bgp_ssh_converter(
        hostname=task.host.name, cmd_output=output_dict, options=options)
コード例 #7
0
def _iosxr_facts_netconf_converter(hostname: str,
                                   cmd_output,
                                   options={}) -> Facts:

    if verbose_mode(user_value=os.environ.get("NETESTS_VERBOSE", NOT_SET),
                    needed_value=LEVEL5):
        printline()
        print(type(cmd_output))
        print(cmd_output)

    hostname = NOT_SET
    domain = NOT_SET
    version = NOT_SET
    serial = NOT_SET
    model = NOT_SET
    interfaces_lst = list()

    facts = Facts(hostname=hostname,
                  domain=domain,
                  version=version,
                  build=NOT_SET,
                  serial=serial,
                  base_mac=NOT_SET,
                  memory=NOT_SET,
                  vendor="Cisco",
                  model=model,
                  interfaces_lst=interfaces_lst,
                  options=options)

    if verbose_mode(user_value=os.environ.get("NETESTS_VERBOSE", NOT_SET),
                    needed_value=LEVEL1):
        printline()
        PP.pprint(facts.to_json())

    return facts
コード例 #8
0
def _juniper_facts_netconf_converter(hostname: str(), cmd_output,
                                     options={}) -> Facts:

    if verbose_mode(user_value=os.environ.get("NETESTS_VERBOSE", NOT_SET),
                    needed_value=LEVEL5):
        printline()
        PP.pprint(cmd_output.get(FACTS_SYS_DICT_KEY))
        print(ElementTree.tostring(cmd_output.get(FACTS_INT_DICT_KEY)))

    interfaces_lst = list()
    for i in format_xml_output(cmd_output.get(FACTS_INT_DICT_KEY)).get(
            'interface-information').get('physical-interface'):
        interfaces_lst.append(i.get('name'))

    facts = Facts(
        hostname=cmd_output.get(FACTS_SYS_DICT_KEY).get('hostname', NOT_SET),
        domain=cmd_output.get(FACTS_SYS_DICT_KEY).get('domain', NOT_SET),
        build=NOT_SET,
        version=cmd_output.get(FACTS_SYS_DICT_KEY).get('version', NOT_SET),
        serial=cmd_output.get(FACTS_SYS_DICT_KEY).get('serialnumber', NOT_SET),
        base_mac=NOT_SET,
        memory=NOT_SET,
        vendor="Juniper",
        model=cmd_output.get(FACTS_SYS_DICT_KEY).get('model', NOT_SET).upper(),
        interfaces_lst=interfaces_lst,
        options=options)

    if verbose_mode(user_value=os.environ.get("NETESTS_VERBOSE", NOT_SET),
                    needed_value=LEVEL1):
        printline()
        PP.pprint(facts.to_json())

    return facts
コード例 #9
0
def _cumulus_get_bgp_api(task, options={}):
    output_dict = dict()
    output_dict['default'] = exec_http_call_cumulus(
        hostname=task.host.hostname,
        port=task.host.port,
        username=task.host.username,
        password=task.host.password,
        cumulus_cmd=CUMULUS_API_GET_BGP,
        secure_api=task.host.get('secure_api', True))
    if verbose_mode(user_value=os.environ.get("NETESTS_VERBOSE", NOT_SET),
                    needed_value=LEVEL2):
        print(output_dict['default'])

    for vrf in task.host[VRF_NAME_DATA_KEY].keys():
        if vrf not in VRF_DEFAULT_RT_LST:
            output_dict[vrf] = exec_http_call_cumulus(
                hostname=task.host.hostname,
                port=task.host.port,
                username=task.host.username,
                password=task.host.password,
                cumulus_cmd=CUMULUS_API_GET_BGP_VRF.format(vrf),
                secure_api=task.host.get('secure_api', True))
            if verbose_mode(user_value=os.environ.get("NETESTS_VERBOSE",
                                                      NOT_SET),
                            needed_value=LEVEL2):
                print_result(output_dict[vrf])

    task.host[BGP_SESSIONS_HOST_KEY] = _cumulus_bgp_api_converter(
        hostname=task.host.name, cmd_output=output_dict, options=options)
コード例 #10
0
def _arista_get_vlan_ssh(task, options={}):
    outputs_dict = dict()

    output_get = task.run(name=f"{ARISTA_GET_VLAN}",
                          task=netmiko_send_command,
                          command_string=ARISTA_GET_VLAN)
    if verbose_mode(user_value=os.environ.get("NETESTS_VERBOSE", NOT_SET),
                    needed_value=LEVEL2):
        print(output_get.result)

    output_get_ip = task.run(name=f"{ARISTA_GET_IP_VLAN}",
                             task=netmiko_send_command,
                             command_string=ARISTA_GET_IP_VLAN)
    if verbose_mode(user_value=os.environ.get("NETESTS_VERBOSE", NOT_SET),
                    needed_value=LEVEL2):
        print(output_get_ip.result)

    output_get_int = task.run(name=f"{ARISTA_GET_INT_VLAN}",
                              task=netmiko_send_command,
                              command_string=ARISTA_GET_INT_VLAN)
    if verbose_mode(user_value=os.environ.get("NETESTS_VERBOSE", NOT_SET),
                    needed_value=LEVEL2):
        print(output_get_int.result)

    if output_get.result != "" and output_get_ip.result != "" and output_get_int.result != "":
        outputs_dict[VLAN_GET_L2] = json.loads(output_get.result)
        outputs_dict[VLAN_GET_L3] = json.loads(output_get_ip.result)
        outputs_dict[VLAN_GET_INT] = json.loads(output_get_int.result)

    task.host[VLAN_DATA_HOST_KEY] = _arista_vlan_ssh_converter(
        cmd_output=outputs_dict, options=options)
コード例 #11
0
def _ios_facts_api_converter(hostname: str, cmd_output, options={}) -> Facts:

    if verbose_mode(user_value=os.environ.get("NETESTS_VERBOSE", NOT_SET),
                    needed_value=LEVEL5):
        printline()
        print(type(cmd_output))
        PP.pprint(json.loads(cmd_output))

    hostname = NOT_SET
    domain = NOT_SET
    version = NOT_SET
    model = NOT_SET
    serial = NOT_SET
    interfaces_lst = list()
    if not isinstance(cmd_output, dict):
        cmd_output = json.loads(cmd_output)
    if (isinstance(cmd_output, dict)
            and 'Cisco-IOS-XE-native:native' in cmd_output.keys()):
        hostname = cmd_output.get('Cisco-IOS-XE-native:native') \
                             .get('hostname')
        domain = cmd_output.get('Cisco-IOS-XE-native:native') \
                           .get('ip') \
                           .get('domain') \
                           .get('name')
        version = cmd_output.get('Cisco-IOS-XE-native:native') \
                            .get('version')
        serial = cmd_output.get('Cisco-IOS-XE-native:native') \
                           .get('license') \
                           .get('udi') \
                           .get('sn')
        model = cmd_output.get('Cisco-IOS-XE-native:native') \
                          .get('license') \
                          .get('udi') \
                          .get('pid')
        for t in cmd_output.get('Cisco-IOS-XE-native:native') \
                           .get('interface').keys():
            for i in cmd_output.get('Cisco-IOS-XE-native:native') \
                               .get('interface') \
                               .get(t):
                interfaces_lst.append(f"{t}{i.get('name')}")

    facts = Facts(hostname=hostname,
                  domain=domain,
                  version=version,
                  build=NOT_SET,
                  serial=serial,
                  base_mac=NOT_SET,
                  memory=NOT_SET,
                  vendor="Cisco",
                  model=model,
                  interfaces_lst=interfaces_lst,
                  options=options)

    if verbose_mode(user_value=os.environ.get("NETESTS_VERBOSE", NOT_SET),
                    needed_value=LEVEL1):
        printline()
        PP.pprint(facts.to_json())

    return facts
コード例 #12
0
def _juniper_vrf_api_converter(hostname: str,
                               cmd_output: list,
                               options={}) -> ListVRF:
    if verbose_mode(user_value=os.environ.get("NETESTS_VERBOSE", NOT_SET),
                    needed_value=LEVEL5):
        printline()
        print(type(cmd_output))
        print(cmd_output)

    cmd_output = format_xml_output(cmd_output)

    if verbose_mode(user_value=os.environ.get("NETESTS_VERBOSE", NOT_SET),
                    needed_value=LEVEL4):
        printline()
        print(type(cmd_output))
        PP.pprint(cmd_output)

    vrf_list = ListVRF(vrf_lst=list())

    for vrf in cmd_output.get('instance-information') \
            .get('instance-core'):
        if _juniper_vrf_filter(vrf.get('instance-name')):
            rd = NOT_SET,
            rt_imp = NOT_SET
            rt_exp = NOT_SET
            imp_targ = NOT_SET
            exp_targ = NOT_SET
            if "instance-vrf" in vrf.keys():
                rd = vrf.get('instance-vrf') \
                        .get('route-distinguisher', NOT_SET)
                rt_imp = vrf.get('instance-vrf') \
                            .get('vrf-import', NOT_SET)
                rt_exp = vrf.get('instance-vrf') \
                            .get('vrf-export', NOT_SET)
                imp_targ = vrf.get('instance-vrf') \
                              .get('vrf-import-target', NOT_SET)
                exp_targ = vrf.get('instance-vrf') \
                              .get('vrf-export-target', NOT_SET)

            vrf_list.vrf_lst.append(
                VRF(vrf_name=_juniper_vrf_default_mapping(
                    vrf.get('instance-name')),
                    vrf_id=vrf.get('router-id', NOT_SET),
                    vrf_type=vrf.get('instance-type', NOT_SET),
                    l3_vni=NOT_SET,
                    rd=rd,
                    rt_imp=rt_imp,
                    rt_exp=rt_exp,
                    imp_targ=imp_targ,
                    exp_targ=exp_targ,
                    options=options))

    if verbose_mode(user_value=os.environ.get("NETESTS_VERBOSE", NOT_SET),
                    needed_value=LEVEL1):
        printline()
        print(f">>>>> {hostname}")
        PP.pprint(vrf_list.to_json())

    return vrf_list
コード例 #13
0
def _juniper_get_bgp_ssh(task, options={}):
    output_dict = dict()
    output_dict["default"] = dict()
    output = task.run(name=f"{JUNOS_GET_BGP}",
                      task=netmiko_send_command,
                      command_string=JUNOS_GET_BGP)
    if verbose_mode(user_value=os.environ.get("NETESTS_VERBOSE", NOT_SET),
                    needed_value=LEVEL2):
        print_result(output)

    if output.result != "" and "BGP is not running" not in output.result:
        output_dict["default"]["bgp"] = output.result

    output = task.run(
        name=f"{JUNOS_GET_BGP_RID}",
        task=netmiko_send_command,
        command_string=JUNOS_GET_BGP_RID,
    )
    if verbose_mode(user_value=os.environ.get("NETESTS_VERBOSE", NOT_SET),
                    needed_value=LEVEL2):
        print_result(output)

    if output.result != "" and "BGP is not running" not in output.result:
        output_dict["default"]["rid"] = output.result

    for vrf in task.host[VRF_NAME_DATA_KEY].keys():
        if vrf not in VRF_DEFAULT_RT_LST:
            output = task.run(
                name=JUNOS_GET_BGP_VRF.format(vrf),
                task=netmiko_send_command,
                command_string=JUNOS_GET_BGP_VRF.format(vrf),
            )
            if verbose_mode(user_value=os.environ.get("NETESTS_VERBOSE",
                                                      NOT_SET),
                            needed_value=LEVEL2):
                print_result(output)

            if (output.result != ""
                    and "BGP is not running" not in output.result):
                output_dict[vrf] = dict()
                output_dict[vrf]["bgp"] = output.result

                output = task.run(
                    name=JUNOS_GET_BGP_VRF_RID.format(vrf),
                    task=netmiko_send_command,
                    command_string=JUNOS_GET_BGP_VRF_RID.format(vrf),
                )
                if verbose_mode(user_value=os.environ.get(
                        "NETESTS_VERBOSE", NOT_SET),
                                needed_value=LEVEL2):
                    print_result(output)

                if (output.result != ""
                        and "BGP is not running" not in output.result):
                    output_dict[vrf]["rid"] = output.result

    task.host[BGP_SESSIONS_HOST_KEY] = _juniper_bgp_ssh_converter(
        hostname=task.host.name, cmd_output=output_dict, options=options)
コード例 #14
0
ファイル: converter.py プロジェクト: mirzawaqasahmed/netests
def _extreme_vsp_bgp_ssh_converter(hostname: str,
                                   cmd_output,
                                   options={}) -> BGP:

    if verbose_mode(user_value=os.environ.get("NETESTS_VERBOSE", NOT_SET),
                    needed_value=LEVEL3):
        printline()
        PP.pprint(cmd_output)

    bgp_sessions_vrf_lst = ListBGPSessionsVRF(list())

    if cmd_output is not None:
        for vrf in cmd_output:
            cmd_output[vrf] = parse_textfsm(
                content=str(cmd_output[vrf]),
                template_file="extreme_vsp_show_ip_bgp_summary.textfsm")
            bgp_sessions_lst = ListBGPSessions(bgp_sessions=list())
            asn = NOT_SET
            router_id = NOT_SET

            for v in cmd_output.get(vrf):
                if v[3] != '':
                    asn = v[1]
                    router_id = v[2]
                    bgp_sessions_lst.bgp_sessions.append(
                        BGPSession(
                            src_hostname=hostname,
                            peer_ip=v[3],
                            peer_hostname=NOT_SET,
                            remote_as=v[4],
                            state_brief=get_bgp_state_brief(v[5]),
                            session_state=v[5],
                            state_time=_extreme_vsp_peer_uptime_converter(
                                day=v[13],
                                hour=v[14],
                                min=v[15],
                                sec=v[16],
                            ),
                            prefix_received=NOT_SET,
                        ))

            bgp_sessions_vrf_lst.bgp_sessions_vrf.append(
                BGPSessionsVRF(
                    vrf_name=vrf,
                    as_number=asn,
                    router_id=router_id,
                    bgp_sessions=bgp_sessions_lst,
                ))

    bgp = BGP(hostname=hostname, bgp_sessions_vrf_lst=bgp_sessions_vrf_lst)

    if verbose_mode(user_value=os.environ.get("NETESTS_VERBOSE", NOT_SET),
                    needed_value=LEVEL1):
        printline()
        print(f">>>>> {hostname}")
        PP.pprint(bgp.to_json())

    return bgp
コード例 #15
0
def _cumulus_bgp_api_converter(hostname: str, cmd_output, options={}) -> BGP:

    bgp_sessions_vrf_lst = ListBGPSessionsVRF(list())

    for k, v in cmd_output.items():
        if not isinstance(v, dict):
            v = json.loads(v)
        if verbose_mode(user_value=os.environ.get("NETESTS_VERBOSE", NOT_SET),
                        needed_value=LEVEL3):
            printline()
            PP.pprint(v)

        peer = False
        if ('ipv4 unicast' in v.keys()
                and 'ipv4Unicast' in v.get('ipv4 unicast').keys() and 'peers'
                in v.get('ipv4 unicast').get('ipv4Unicast').keys()):
            sub_dict = v.get('ipv4 unicast').get('ipv4Unicast')
            peer = True

        elif ('ipv4 unicast' in v.keys()
              and 'peers' in v.get('ipv4 unicast').keys()):
            sub_dict = v.get('ipv4 unicast')
            peer = True

        if peer:
            bgp_vrf = BGPSessionsVRF(
                vrf_name=k,
                as_number=sub_dict.get('as', NOT_SET),
                router_id=sub_dict.get('routerId', NOT_SET),
                bgp_sessions=ListBGPSessions(bgp_sessions=list()))
            for i, p in sub_dict.get('peers').items():
                bgp_vrf.bgp_sessions.bgp_sessions.append(
                    BGPSession(src_hostname=hostname,
                               peer_ip=i,
                               peer_hostname=p.get('hostname', NOT_SET),
                               remote_as=p.get('remoteAs', NOT_SET),
                               state_brief=get_bgp_state_brief(
                                   p.get('state', NOT_SET)),
                               session_state=p.get('state', NOT_SET),
                               state_time=get_bgp_peer_uptime(
                                   value=p.get('peerUptimeMsec', NOT_SET),
                                   format=BGP_UPTIME_FORMAT_MS),
                               prefix_received=p.get('prefixReceivedCount',
                                                     NOT_SET),
                               options=options))

            bgp_sessions_vrf_lst.bgp_sessions_vrf.append(bgp_vrf)

    bgp = BGP(hostname=hostname, bgp_sessions_vrf_lst=bgp_sessions_vrf_lst)

    if verbose_mode(user_value=os.environ.get("NETESTS_VERBOSE", NOT_SET),
                    needed_value=LEVEL1):
        printline()
        print(f">>>>> {hostname}")
        PP.pprint(bgp.to_json())

    return bgp
コード例 #16
0
def _iosxr_bgp_ssh_converter(hostname: str,
                             cmd_output: dict,
                             options={}) -> BGP:

    bgp_sessions_vrf_lst = ListBGPSessionsVRF(list())

    for k, v in cmd_output.items():
        v['peers'] = parse_textfsm(
            content=v.get('peers'),
            template_file='cisco_xr_show_bgp_neighbors.textfsm')
        v['rid'] = parse_textfsm(content=v.get('rid'),
                                 template_file='cisco_xr_show_bgp.textfsm')
        if verbose_mode(user_value=os.environ.get('NETESTS_VERBOSE', NOT_SET),
                        needed_value=LEVEL3):
            printline()
            print(v)

        bgp_sessions_lst = ListBGPSessions(list())
        asn = NOT_SET
        if len(v['peers']) > 0:
            for i in v['peers']:
                asn = i[3]
                bgp_sessions_lst.bgp_sessions.append(
                    BGPSession(
                        src_hostname=hostname,
                        peer_ip=i[0],
                        peer_hostname=NOT_SET,
                        remote_as=i[2],
                        state_brief=get_bgp_state_brief(i[4]),
                        session_state=i[4],
                        state_time=NOT_SET,
                        prefix_received=NOT_SET,
                    ))

            if len(v['rid']) > 0:
                rid = v['rid'][0][0]
            else:
                rid = NOT_SET

            bgp_sessions_vrf_lst.bgp_sessions_vrf.append(
                BGPSessionsVRF(
                    vrf_name=k,
                    as_number=asn,
                    router_id=rid,
                    bgp_sessions=bgp_sessions_lst,
                ))

    bgp = BGP(hostname=hostname, bgp_sessions_vrf_lst=bgp_sessions_vrf_lst)

    if verbose_mode(user_value=os.environ.get('NETESTS_VERBOSE', NOT_SET),
                    needed_value=LEVEL1):
        printline()
        print(f'>>>>> {hostname}')
        PP.pprint(bgp.to_json())

    return bgp
コード例 #17
0
ファイル: converter.py プロジェクト: mirzawaqasahmed/netests
def _juniper_vrf_netconf_converter(hostname: str(), cmd_output,
                                   options={}) -> ListVRF:
    if isinstance(cmd_output, lxml.etree._Element):
        cmd_output = json.dumps(
            xmltodict.parse(ElementTree.tostring(cmd_output)))
    elif isinstance(cmd_output, str):
        cmd_output = json.dumps(xmltodict.parse(cmd_output))

    cmd_output = json.loads(cmd_output)

    if verbose_mode(user_value=os.environ.get("NETESTS_VERBOSE", NOT_SET),
                    needed_value=LEVEL4):
        printline()
        PP.pprint(cmd_output)

    vrf_list = ListVRF(list())

    for vrf in cmd_output.get('instance-information') \
            .get('instance-core'):
        if _juniper_vrf_filter(vrf.get('instance-name')):
            rd = NOT_SET,
            rt_imp = NOT_SET
            rt_exp = NOT_SET
            imp_targ = NOT_SET
            exp_targ = NOT_SET
            if "instance-vrf" in vrf.keys():
                rd = vrf.get('instance-vrf') \
                        .get('route-distinguisher', NOT_SET)
                rt_imp = vrf.get('instance-vrf') \
                            .get('vrf-import', NOT_SET)
                rt_exp = vrf.get('instance-vrf') \
                            .get('vrf-export', NOT_SET)
                imp_targ = vrf.get('instance-vrf') \
                              .get('vrf-import-target', NOT_SET)
                exp_targ = vrf.get('instance-vrf') \
                              .get('vrf-export-target', NOT_SET)

            vrf_list.vrf_lst.append(
                VRF(vrf_name=_juniper_vrf_default_mapping(
                    vrf.get('instance-name')),
                    vrf_id=vrf.get('router-id', NOT_SET),
                    vrf_type=vrf.get('instance-type', NOT_SET),
                    l3_vni=NOT_SET,
                    rd=rd,
                    rt_imp=rt_imp,
                    rt_exp=rt_exp,
                    imp_targ=imp_targ,
                    exp_targ=exp_targ,
                    options=options))

    if verbose_mode(user_value=os.environ.get("NETESTS_VERBOSE", NOT_SET),
                    needed_value=LEVEL1):
        printline()
        PP.pprint(vrf_list.to_json())

    return vrf_list
コード例 #18
0
ファイル: verbose.py プロジェクト: mirzawaqasahmed/netests
def step_impl(context):
    assert verbose_mode(user_value=context.level5, needed_value=LEVEL1)

    assert verbose_mode(user_value=context.level5, needed_value=LEVEL2)

    assert verbose_mode(user_value=context.level5, needed_value=LEVEL3)

    assert verbose_mode(user_value=context.level5, needed_value=LEVEL4)

    assert verbose_mode(user_value=context.level5, needed_value=LEVEL5)
コード例 #19
0
def _juniper_get_facts_ssh(task, options={}):
    outputs_dict = dict()

    output = task.run(name=f"{JUNOS_GET_FACTS}",
                      task=netmiko_send_command,
                      command_string=JUNOS_GET_FACTS)
    if verbose_mode(user_value=os.environ.get("NETESTS_VERBOSE", NOT_SET),
                    needed_value=LEVEL2):
        print_result(output)

    if output.result != "":
        outputs_dict[FACTS_SYS_DICT_KEY] = (json.loads(output.result))

    output = task.run(name=f"{JUNOS_GET_INT}",
                      task=netmiko_send_command,
                      command_string=JUNOS_GET_INT)
    if verbose_mode(user_value=os.environ.get("NETESTS_VERBOSE", NOT_SET),
                    needed_value=LEVEL2):
        print_result(output)

    if output.result != "":
        outputs_dict[FACTS_INT_DICT_KEY] = (json.loads(output.result))

    output = task.run(name=f"{JUNOS_GET_MEMORY}",
                      task=netmiko_send_command,
                      command_string=JUNOS_GET_MEMORY)
    if verbose_mode(user_value=os.environ.get("NETESTS_VERBOSE", NOT_SET),
                    needed_value=LEVEL2):
        print_result(output)

    if output.result != "":
        outputs_dict[FACTS_MEMORY_DICT_KEY] = (json.loads(output.result))

    output = task.run(name=f"{JUNOS_GET_CONFIG_SYSTEM}",
                      task=netmiko_send_command,
                      command_string=JUNOS_GET_CONFIG_SYSTEM)
    if verbose_mode(user_value=os.environ.get("NETESTS_VERBOSE", NOT_SET),
                    needed_value=LEVEL2):
        print_result(output)

    if output.result != "":
        outputs_dict[FACTS_CONFIG_DICT_KEY] = (json.loads(output.result))

    output = task.run(name=f"{JUNOS_GET_SERIAL}",
                      task=netmiko_send_command,
                      command_string=JUNOS_GET_SERIAL)
    if verbose_mode(user_value=os.environ.get("NETESTS_VERBOSE", NOT_SET),
                    needed_value=LEVEL2):
        print_result(output)

    if output.result != "":
        outputs_dict[FACTS_SERIAL_DICT_KEY] = (json.loads(output.result))

    task.host[FACTS_DATA_HOST_KEY] = _juniper_facts_ssh_converter(
        hostname=task.host.name, cmd_output=outputs_dict, options=options)
コード例 #20
0
def _arista_vrf_ssh_converter(
    hostname: str(),
    cmd_output,
    options={}
) -> ListVRF:

    if not isinstance(cmd_output, dict):
        cmd_output = json.loads(cmd_output)

    if verbose_mode(
        user_value=os.environ.get("NETESTS_VERBOSE", NOT_SET),
        needed_value=LEVEL3
    ):
        printline()
        print(cmd_output)

    vrf_list = ListVRF(list())
    for vrf_name, facts in cmd_output.get('vrfs').items():
        if (
            facts.get('routeDistinguisher', NOT_SET) == NOT_SET or
            facts.get('routeDistinguisher', NOT_SET) == ''
        ):
            rd = NOT_SET
        else:
            rd = facts.get('routeDistinguisher', NOT_SET)

        vrf_obj = VRF(
            vrf_name=vrf_name,
            vrf_id=NOT_SET,
            vrf_type=NOT_SET,
            l3_vni=NOT_SET,
            rd=rd,
            rt_imp=NOT_SET,
            rt_exp=NOT_SET,
            imp_targ=NOT_SET,
            exp_targ=NOT_SET,
            options=options
        )

        vrf_list.vrf_lst.append(
            vrf_obj
        )

    if verbose_mode(
        user_value=os.environ.get("NETESTS_VERBOSE", NOT_SET),
        needed_value=LEVEL1
    ):
        printline()
        print(f">>>>> {hostname}")
        PP.pprint(vrf_list.to_json())

    return vrf_list
コード例 #21
0
def _ios_vrf_ssh_converter(hostname: str(), cmd_output, options={}) -> ListVRF:
    cmd_output = re.sub(pattern=r"communities[\n\r]\s+RT",
                        repl="communities:RT",
                        string=cmd_output)

    if verbose_mode(user_value=os.environ.get("NETESTS_VERBOSE", NSET),
                    needed_value=LEVEL4):
        printline()
        print(cmd_output)

    template = open(f"{TEXTFSM_PATH}cisco_ios_show_ip_vrf_detail.textfsm")
    results_template = textfsm.TextFSM(template)
    # Example : [
    #   ['mgmt', '1', '<not set>'],
    #   ['tenant-1', '2', '10.255.255.103:103']
    # ]
    parsed_results = results_template.ParseText(cmd_output)

    vrf_list = ListVRF(list())
    # Add the default VRF maually
    vrf_list.vrf_lst.append(
        VRF(vrf_name="default",
            vrf_id="0",
            vrf_type=NSET,
            l3_vni=NSET,
            rd=NSET,
            rt_imp=NSET,
            rt_exp=NSET,
            exp_targ=NSET,
            imp_targ=NSET,
            options=options))

    for l in parsed_results:
        vrf_list.vrf_lst.append(
            VRF(vrf_name=l[0] if l[0] != "<not set>" and l[0] != '' else NSET,
                vrf_id=l[1] if l[1] != "<not set>" and l[1] != '' else NSET,
                vrf_type=NSET,
                l3_vni=NSET,
                rd=l[2] if l[2] != "<not set>" and l[2] != '' else NSET,
                rt_imp=l[5] if l[5] != "<not set>" and l[5] != '' else NSET,
                rt_exp=l[6] if l[6] != "<not set>" and l[6] != '' else NSET,
                exp_targ=NSET,
                imp_targ=NSET,
                options=options))

    if verbose_mode(user_value=os.environ.get("NETESTS_VERBOSE", NSET),
                    needed_value=LEVEL1):
        printline()
        print(f">>>>> {hostname}")
        PP.pprint(vrf_list.to_json())

    return vrf_list
コード例 #22
0
def _juniper_get_bgp_api(task, options={}):
    output_dict = dict()
    output_dict['default'] = dict()
    output_dict['default']['bgp'] = exec_http_call_juniper(
        hostname=task.host.hostname,
        port=task.host.port,
        username=task.host.username,
        password=task.host.password,
        endpoint="get-bgp-neighbor-information?exact-instance=master",
        secure_api=task.host['secure_api'])
    output_dict['default']['rid'] = exec_http_call_juniper(
        hostname=task.host.hostname,
        port=task.host.port,
        username=task.host.username,
        password=task.host.password,
        endpoint="get-instance-information?instance-name=master&detail=",
        secure_api=task.host['secure_api'])
    if verbose_mode(user_value=os.environ.get("NETESTS_VERBOSE", NOT_SET),
                    needed_value=LEVEL5):
        printline()
        print(output_dict['default']['rid'])
        print(output_dict['default']['rid'])

    for v in task.host[VRF_NAME_DATA_KEY].keys():
        if v not in VRF_DEFAULT_RT_LST:
            output_dict[v] = dict()
            output_dict[v]['bgp'] = exec_http_call_juniper(
                hostname=task.host.hostname,
                port=task.host.port,
                username=task.host.username,
                password=task.host.password,
                endpoint=f"get-bgp-neighbor-information?exact-instance={v}",
                secure_api=task.host['secure_api'])
            output_dict[v]['rid'] = exec_http_call_juniper(
                hostname=task.host.hostname,
                port=task.host.port,
                username=task.host.username,
                password=task.host.password,
                endpoint=f"get-instance-information?instance-name={v}&detail=",
                secure_api=task.host['secure_api'])
            if verbose_mode(user_value=os.environ.get("NETESTS_VERBOSE",
                                                      NOT_SET),
                            needed_value=LEVEL5):
                printline()
                print(output_dict[v]['bgp'])
                print(output_dict[v]['rid'])

    task.host[BGP_SESSIONS_HOST_KEY] = _juniper_bgp_api_converter(
        hostname=task.host.name, cmd_output=output_dict, options=options)
コード例 #23
0
def _nxos_vrf_ssh_converter(
    hostname: str(),
    cmd_output,
    options={}
) -> ListVRF:
    vrf_list = ListVRF(list())
    for vrf in cmd_output.get('TABLE_vrf', NOT_SET).get('ROW_vrf'):
        vrf_list.vrf_lst.append(
            VRF(
                vrf_name=vrf.get('vrf_name', NOT_SET),
                vrf_id=vrf.get('vrf_id', NOT_SET),
                vrf_type=NOT_SET,
                l3_vni=NOT_SET,
                rd=vrf.get('rd') if vrf.get('rd') != '0:0' else NOT_SET,
                rt_imp=NOT_SET,
                rt_exp=NOT_SET,
                imp_targ=NOT_SET,
                exp_targ=NOT_SET,
                options=options
            )
        )

    if verbose_mode(
        user_value=os.environ.get("NETESTS_VERBOSE", NOT_SET),
        needed_value=LEVEL1
    ):
        printline()
        print(f">>>>> {hostname}")
        PP.pprint(vrf_list.to_json())

    return vrf_list
コード例 #24
0
def run_ipv4(nr: Nornir, test_to_execute: dict) -> bool:
    exit_value = True
    if TEST_TO_EXC_IPV4_KEY in test_to_execute.keys():
        if test_to_execute[TEST_TO_EXC_IPV4_KEY].get("test", False):
            get_ipv4(
                nr=nr,
                filters=test_to_execute.get(TEST_TO_EXC_IPV4_KEY).get(
                    "filters", dict({})),
            )
            ipv4_yaml_data = open_file(
                path=f"{PATH_TO_VERITY_FILES}{IPV4_SRC_FILENAME}")
            same = compare_ipv4(nr, ipv4_yaml_data)
            if (test_to_execute[TEST_TO_EXC_IPV4_KEY] and same is False):
                exit_value = False
            print(
                f"{HEADER} IPv4 addresses defined in"
                f"{PATH_TO_VERITY_FILES}{IPV4_SRC_FILENAME} work = {same} !!")
        else:
            print(f"{HEADER} IPv4 addresses have not been executed !!")
    else:
        if verbose_mode(user_value=os.environ.get("NETESTS_VERBOSE", NOT_SET),
                        needed_value=LEVEL1):
            print(f"{HEADER} IPv4 addresses key is not defined in"
                  f"{PATH_TO_VERITY_FILES}{TEST_TO_EXECUTE_FILENAME} !!")

    return exit_value
コード例 #25
0
ファイル: bond_run.py プロジェクト: mirzawaqasahmed/netests
def run_bond(nr: Nornir, test_to_execute: dict):
    exit_value = True
    if TEST_TO_EXC_BOND_KEY in test_to_execute.keys():
        if test_to_execute[TEST_TO_EXC_BOND_KEY].get("test"):
            get_bond(
                nr=nr,
                filters=test_to_execute.get(TEST_TO_EXC_BOND_KEY).get(
                    "filters", dict({})),
            )
            bond_yaml_data = open_file(
                path=f"{PATH_TO_VERITY_FILES}{BOND_SRC_FILENAME}")
            same = compare_bond(nr=nr, bond_yaml_data=bond_yaml_data)
            if (test_to_execute[TEST_TO_EXC_BOND_KEY] and same is False):
                exit_value = False
            print(
                f"{HEADER} BOND defined in"
                f"{PATH_TO_VERITY_FILES}{BOND_SRC_FILENAME} work = {same} !!")
        else:
            print(f"{HEADER} BOND have not been executed !!")
    else:
        if verbose_mode(user_value=os.environ.get("NETESTS_VERBOSE", NOT_SET),
                        needed_value=LEVEL1):
            print(f"{HEADER} BOND key not found in"
                  f"{PATH_TO_VERITY_FILES}{TEST_TO_EXECUTE_FILENAME}  !!")

    return exit_value
コード例 #26
0
ファイル: converter.py プロジェクト: mirzawaqasahmed/netests
def _napalm_facts_converter(hostname: str,
                            platform: str,
                            cmd_output: json,
                            options={}) -> Facts:
    if cmd_output is None:
        return Facts()

    i = len(f"{str(cmd_output.get('facts').get('hostname'))}.")

    facts = Facts(
        hostname=cmd_output.get('facts').get('hostname')
        if cmd_output.get("facts").get("hostname", NOT_SET) != '' else NOT_SET,
        domain=cmd_output.get("facts").get("fqdn", NOT_SET)[i:]
        if cmd_output.get("facts").get("fqdn", NOT_SET) != '' else NOT_SET,
        version=cmd_output.get("facts").get("os_version", NOT_SET) if
        cmd_output.get("facts").get("os_version", NOT_SET) != '' else NOT_SET,
        serial=cmd_output.get("facts").get("serial_number", NOT_SET)
        if cmd_output.get("facts").get("serial_number", NOT_SET) != '' else
        NOT_SET,
        base_mac=NOT_SET,
        memory=NOT_SET,
        vendor=cmd_output.get("facts").get("vendor", NOT_SET)
        if cmd_output.get("facts").get("vendor", NOT_SET) != '' else NOT_SET,
        model=cmd_output.get("facts").get("model", NOT_SET)
        if cmd_output.get("facts").get("model", NOT_SET) != '' else NOT_SET,
        interfaces_lst=cmd_output.get('facts').get('interface_list') if
        cmd_output.get("facts").get("interface_list", NOT_SET) != '' else [],
        options=options)

    if verbose_mode(user_value=os.environ.get("NETESTS_VERBOSE", NOT_SET),
                    needed_value=LEVEL1):
        printline()
        PP.pprint(facts.to_json())

    return facts
コード例 #27
0
def _cumulus_get_vrf_api(task, options={}):
    res = requests.post(
        url=f"https://{task.host.hostname}:{task.host.port}/nclu/v1/rpc",
        data=json.dumps(
            {
                "cmd": f"{CUMULUS_API_GET_VRF}"
            }),
        headers={'content-type': 'application/json'},
        auth=requests.auth.HTTPBasicAuth(
            f"{task.host.username}",
            f"{task.host.password}"
        ),
        verify=False
    )

    if verbose_mode(
        user_value=os.environ.get("NETESTS_VERBOSE", NOT_SET),
        needed_value=LEVEL3
    ):
        print(type(res.status_code), res.status_code)
        print(type(res.content), res.content)

    if res.status_code != 200:
        raise NetestsHTTPStatusCodeError()

    task.host[VRF_DATA_KEY] = _cumulus_vrf_api_converter(
        hostname=task.host.name,
        cmd_output=res.content,
        options=options
    )
コード例 #28
0
def _arista_get_facts_api(task, options={}):
    c = pyeapi.connect(
        transport=task.host.get('secure_api', 'https'),
        host=task.host.hostname,
        username=task.host.username,
        password=task.host.password,
        port=task.host.port
    )
    output = c.execute([
        ARISTA_GET_FACTS,
        ARISTA_GET_INT,
        ARISTA_GET_DOMAIN
    ])

    if verbose_mode(
        user_value=os.environ.get("NETESTS_VERBOSE", NOT_SET),
        needed_value=LEVEL2
    ):
        printline()
        print(output)

    task.host[FACTS_DATA_HOST_KEY] = _arista_facts_api_converter(
        hostname=task.host.name,
        cmd_output=output,
        options=options
    )
コード例 #29
0
def _arista_bgp_api_converter(hostname: str, cmd_output, options={}) -> BGP:

    bgp_sessions_vrf_lst = ListBGPSessionsVRF(list())

    if verbose_mode(user_value=os.environ.get("NETESTS_VERBOSE", NOT_SET),
                    needed_value=LEVEL3):
        printline()
        PP.pprint(cmd_output)

    bgp_sessions_vrf_lst = ListBGPSessionsVRF(list())

    for vrf in cmd_output.get('result', []):
        if 'vrfs' in vrf.keys() and len(vrf.get('vrfs').keys()) > 0:
            bgp_sessions_lst = ListBGPSessions(list())
            for name, facts in vrf.get("vrfs", NOT_SET).items():
                for n, f in facts.get('peers').items():
                    bgp_sessions_lst.bgp_sessions.append(
                        BGPSession(
                            src_hostname=hostname,
                            peer_ip=n,
                            peer_hostname=f.get("hostname", NOT_SET),
                            remote_as=f.get("asn", NOT_SET),
                            state_brief=get_bgp_state_brief(
                                state=f.get('peerState')),
                            session_state=f.get("peerState", NOT_SET),
                            state_time=f.get("upDownTime", NOT_SET),
                            prefix_received=f.get("prefixReceived", NOT_SET),
                        ))

                bgp_sessions_vrf_lst.bgp_sessions_vrf.append(
                    BGPSessionsVRF(
                        vrf_name=name,
                        as_number=facts.get('asn', NOT_SET),
                        router_id=facts.get("routerId", NOT_SET),
                        bgp_sessions=bgp_sessions_lst,
                    ))

    bgp = BGP(hostname=hostname, bgp_sessions_vrf_lst=bgp_sessions_vrf_lst)

    if verbose_mode(user_value=os.environ.get("NETESTS_VERBOSE", NOT_SET),
                    needed_value=LEVEL1):
        printline()
        print(f">>>>> {hostname}")
        PP.pprint(bgp.to_json())

    return bgp
コード例 #30
0
def _juniper_get_bgp_netconf(task, options={}):
    output_dict = dict()
    output_dict['default'] = dict()
    with Device(
            host=task.host.hostname,
            port=task.host.port,
            user=task.host.username,
            passwd=task.host.password,
    ) as m:

        output_dict['default']['bgp'] = m.rpc.get_bgp_neighbor_information(
            exact_instance="master")
        output_dict['default']['rid'] = m.rpc.get_instance_information(
            detail=True, instance_name="master")
        if verbose_mode(user_value=os.environ.get("NETESTS_VERBOSE", NOT_SET),
                        needed_value=LEVEL5):
            printline()
            print(ElementTree.tostring(output_dict['default']['bgp']))
            print(ElementTree.tostring(output_dict['default']['rid']))

        ElementTree.fromstring(
            ElementTree.tostring(output_dict['default']['bgp']))
        ElementTree.fromstring(
            ElementTree.tostring(output_dict['default']['rid']))

        for vrf in task.host[VRF_NAME_DATA_KEY].keys():
            if vrf not in VRF_DEFAULT_RT_LST:
                output_dict[vrf] = dict()
                output_dict[vrf]['bgp'] = m.rpc.get_bgp_neighbor_information(
                    exact_instance=vrf)
                output_dict[vrf]['rid'] = m.rpc.get_instance_information(
                    detail=True, instance_name=vrf)
                if verbose_mode(user_value=os.environ.get(
                        "NETESTS_VERBOSE", NOT_SET),
                                needed_value=LEVEL5):
                    printline()
                    print(ElementTree.tostring(output_dict[vrf]['bgp']))
                    print(ElementTree.tostring(output_dict[vrf]['rid']))

                ElementTree.fromstring(
                    ElementTree.tostring(output_dict[vrf]['bgp']))
                ElementTree.fromstring(
                    ElementTree.tostring(output_dict[vrf]['rid']))

    task.host[BGP_SESSIONS_HOST_KEY] = _juniper_bgp_netconf_converter(
        hostname=task.host.name, cmd_output=output_dict, options=options)