def filter_ge_sla(nr, sla):
    """
    Filter the hosts inventory, which greater or equal to a SLA integer
    value.

    :param nr: An initialised Nornir inventory, used for processing.
    :param sla: The SLA number to filter on
    :type sla: integer

    :return target_hosts: The targeted nornir hosts after being
    processed through nornir filtering.
    """
    # Execute filter based greater or equal to the SLA integer
    target_hosts = nr.filter(F(sla__ge=sla))
    # Print seperator and header
    print("=" * 50)
    print(f"The hosts with SLA greater or equal to {sla} are:")
    # Iterate over filtered results and printout information
    for host, data in target_hosts.inventory.hosts.items():
        print(f"Host: {Fore.CYAN}{host} " + Fore.RESET +
              f"- SLA: {Fore.CYAN}{data['sla']} " + Fore.RESET +
              f"- Production: {Fore.CYAN}{data['production']}")
    # Print total and seperator
    print(f"Total: {len(target_hosts.inventory.hosts.items())}")
    print("=" * 50)
    # Return filtered hosts
    return target_hosts
Esempio n. 2
0
def main():
    nr = InitNornir(
        config_file='../config.yaml',
        core={'num_workers': 50},
    )
    #insert_creds(nr.inventory)
    ios_filt = ~F(platform="cisco_wlc")
    ios = nr.filter(ios_filt)
    start_time = datetime.now()
    result = ios.run(task=backup)
    elapsed_time = datetime.now() - start_time

    print('-' * 50)
    print("Results")
    print('-' * 50)
    for host, multiresult in result.items():
        if multiresult.failed:
            print(f'{host} - failed, check nornir.log')
            continue
        for r in multiresult:
            if r.name == 'write_file':
                if r.changed:
                    #print(f'{host} - differences found since last backup')
                    diff_time = datetime.now()
                    filename = f'{DIFFDIR}/{host}--{diff_time.strftime("%d-%m-%y-%X")}.txt'
                    with open(filename, 'w') as f:
                        f.write(r.diff)
    print('-' * 50)
    print("Elapsed time: {}".format(elapsed_time))
Esempio n. 3
0
def sync_basetemplate(hostname: Optional[str]=None,
                      device_type: Optional[DeviceType]=None,
                      dry_run: bool=True) -> NornirJobResult:
    """Synchronize base system template to device or device group.

    Args:
        hostname: Hostname of a single device to sync
        device_type: A device group type to sync
        dry_run: Set to true to only perform a NAPALM dry_run of config changes 
    """
    nrresult = None

    nr = cnaas_nms.confpush.nornir_helper.cnaas_init()
    if hostname and isinstance(hostname, str):
        nr_filtered = nr.filter(name=hostname)
    elif device_type and isinstance(device_type, DeviceType):
        group_name = ('T_'+device_type.value)
        nr_filtered = nr.filter(F(groups__contains=group_name))
    else:
        raise ValueError("hostname or device_type must be specified")

    nrresult = nr_filtered.run(task=push_basetemplate)

    return NornirJobResult(
        nrresult = nrresult
    )
Esempio n. 4
0
def main():
	nr = InitNornir()

	# Exercise 2a
	print("\nExercise 2a")
	print("-" * 20)
	arista1 = nr.filter(name="arista1")
	print(arista1.inventory.hosts)
	print("-" * 20)

	print("\nExercise 2b")
	print("-" * 20)
	wan_devs = nr.filter(role="WAN")
	print(wan_devs.inventory.hosts)
	wan_devs = wan_devs.filter(port=22)
	print(wan_devs.inventory.hosts)
	print("-" * 20)
	# Alternatively:
	# wan_devs = nr.filter(role="WAN").filter(port=22)

	print("\nExercise 2c")
	print("-" * 20)
	sfo_f_obj = nr.filter(F(groups__contains="sfo"))
	print(sfo_f_obj.inventory.hosts)
	print("-" * 20)
	print()
def check_ping(IP):
     try:
        if ipaddress.ip_address(IP) not in ipaddress.ip_network('10.90.0.0/16'):
            print("Server IP {0} is not in range for TY6 DC servers".format(IP))
        else:
            SWITCH = nr.filter(F(hostname="10.91.2.4"))
            PING = SWITCH.run(task=napalm_ping, dest=IP)
            if "success" in PING['CS_1'].result:
                print("=======================================================")
                print("Server IP {0} is Pingable".format(IP))
                ARP = SWITCH.run(task=napalm_get, getters=["arp_table"])
                for cs_name in ARP.keys():
                    CS_NAME = cs_name
                    #print(CS_NAME)

                ARP_LIST = ARP[CS_NAME].result['arp_table']
                for i, j in enumerate(ARP_LIST):
                    ALL_MAC = (j['mac'])
                    ALL_INTERFACE = (j['interface'])
                    ALL_IP = (j['ip'])
                    if ALL_IP == IP:
                       INTERFACE = ALL_INTERFACE.split()[1][1:][:-3]
                       MAC = ALL_MAC
                       check_lacp_lldp(INTERFACE,MAC)
            else:
                print("Server IP {0} NOT Pingable".format(IP))
                pass
     except Exception as e:
         print("ERROR:{0}".format(e))
Esempio n. 6
0
def main():
    nr = InitNornir(config_file="config.yaml")
    ios_filt = F(groups__contains="ios")
    nr = nr.filter(ios_filt)

    # Set one of the devices to an invalid password
    nr.inventory.hosts["cisco3"].password = "******"
    my_results = nr.run(task=netmiko_send_command,
                        command_string="show ip int brief")
    print()
    print_result(my_results)
    print()
    print(f"Task failed hosts: {my_results.failed_hosts}")
    print(f"Global failed hosts: {nr.data.failed_hosts}")
    print()

    # Re-set password back to valid value
    nr.inventory.hosts["cisco3"].password = os.environ["NORNIR_PASSWORD"]

    # Re-run only on failed hosts
    print()
    my_results = nr.run(
        task=netmiko_send_command,
        command_string="show ip int brief",
        on_good=False,
        on_failed=True,
    )
    print_result(my_results)
    print()
    print(f"Task failed hosts: {my_results.failed_hosts}")
    print(f"Global failed hosts: {nr.data.failed_hosts}")
    print()
Esempio n. 7
0
def main():
	nr = InitNornir(config_file="config.yaml")
	nr = nr.filter(F(groups__contains="eos"))
	agg_result = nr.run(
			task=netmiko_send_command,
			command_string="show int status",
			use_textfsm=True)
	print()
	print("Exercise 4b - verify structured data")
	print("-" * 20)
	print(type(agg_result["arista1"][0].result))
	print("-" * 20)

	print("\nExercise 4c - final dictionary")
	print("-" * 20)
	combined_data = {}
	for device_name, multi_result in agg_result.items():
		combined_data[device_name] = {}
		device_result = multi_result[0]
		for intf_dict in device_result.result:
			intf_name = intf_dict["port"]
			inner_dict = {
				"status": intf_dict["status"],
				"vlan": intf_dict["vlan"]
			}
			combined_data[device_name][intf_name] = inner_dict
	pprint(combined_data)
	print("-" * 20)
	print()
Esempio n. 8
0
def main():
    nr = InitNornir(config_file="config.yaml")
    nxos = nr.filter(F(platform="nxos"))
    results = nxos.run(task=napalm_get,
                       getters=["config", "facts"],
                       getters_options={"config": {
                           "retrieve": "all"
                       }})
    agg_data = {}
    for host, multi_result in results.items():
        agg_data[host] = {}
        host_results = multi_result[0]

        configs = host_results.result["config"]
        start_config = configs["startup"].split("\n")[4:]
        run_config = configs["running"].split("\n")[4:]

        facts = host_results.result["facts"]

        inner_dict = {}
        if start_config == run_config:
            inner_dict["start_running_match"] = True
        else:
            inner_dict["start_running_match"] = False
        inner_dict["model"] = facts["model"]
        inner_dict["uptime"] = facts["uptime"]
        inner_dict["vendor"] = facts["vendor"]
        agg_data[host] = inner_dict
    print()
    pprint(agg_data)
Esempio n. 9
0
def main():
    nr = InitNornir(config_file="config.yaml")
    eos = nr.filter(F(groups__contains="eos"))
    results = eos.run(task=netmiko_send_command,
                      command_string="show interface status",
                      use_textfsm=True)
    print()
    # create blank dictionary
    agg_data = {}
    # iterate through results items on two keys
    for host, multi_result in results.items():
        # add host key to = blank dictionary
        agg_data[host] = {}
        # unpack the result list item into a seperate var
        task_result = multi_result[0]
        # now iterate over the result dictionary
        for int_dict in task_result.result:
            # set the int_name key value - used later
            int_name = int_dict["port"]
            # create an empty inner dictionary
            inner_dict = {}
            # now create the inner key:value pairs
            inner_dict["status"] = int_dict["status"]
            inner_dict["vlan"] = int_dict["vlan"]
            # finally, set the int_name value to the inner dictonary
            agg_data[host][int_name] = inner_dict
    print("-" * 80)
    pprint(agg_data)
def filter_non_primary_site_type(nr):
    """
    Filter the hosts inventory, which match a site types which
    are not a primary site_type

    :param nr: An initialised Nornir inventory, used for processing.

    :return target_hosts: The targeted nornir hosts after being
    processed through nornir filtering.
    """
    # Execute filter which the site_type of secondary OR tertiary
    target_hosts = nr.filter(F(site_type__any=["tertiary", "secondary"]))
    # Print seperator and header
    print("=" * 50)
    print("The hosts which are at non-primary site types are:")
    # Iterate over filtered results and printout information
    for host, data in target_hosts.inventory.hosts.items():
        print(f"Host: {Fore.CYAN}{host} " + Fore.RESET +
              f"- Site Type: {Fore.CYAN}{data['site_type']} " + Fore.RESET +
              f"- Site Code: {Fore.CYAN}{data['site_code']} " + Fore.RESET +
              f"- Full Name: {Fore.CYAN}{data['full_name']}")
    # Print total and seperator
    print(f"Total: {len(target_hosts.inventory.hosts.items())}")
    print("=" * 50)
    # Return filtered hosts
    return target_hosts
Esempio n. 11
0
def run():

    nr = InitNornir("config.yaml")
    csr1000v = nr.filter(F(groups__contains="csr1000v"))
    results = csr1000v.run(task=push_config)
    print_result(results)
    input("\n\nPress Enter to continue")
def filter_site_type(nr, site_type):
    """
    Filter the hosts inventory, which match a given site type.

    :param nr: An initialised Nornir inventory, used for processing.
    :param site_type: The site_type you want to filter on.
    :type site_type: string

    :return target_hosts: The targeted nornir hosts after being
    processed through nornir filtering.
    """
    # Execute filter based on site type
    target_hosts = nr.filter(F(site_type__eq=site_type))
    # Print seperator and header
    print("=" * 50)
    print(f"The hosts which match site type {site_type} are:")
    # Iterate over filtered results and printout information
    for host, data in target_hosts.inventory.hosts.items():
        print(f"Host: {Fore.CYAN}{host} " + Fore.RESET +
              f"- Site Type: {Fore.CYAN}{data['site_type']} " + Fore.RESET +
              f"- Site Code: {Fore.CYAN}{data['site_code']} " + Fore.RESET +
              f"- Full Name: {Fore.CYAN}{data['full_name']}")
    # Print total and seperator
    print(f"Total: {len(target_hosts.inventory.hosts.items())}")
    print("=" * 50)
    # Return filtered hosts
    return target_hosts
def filter_region(nr, region):
    """
    Filter the hosts inventory, which match a given region.

    :param nr: An initialised Nornir inventory, used for processing.
    :param region: The region you want to filter on.
    :type region: string

    :return target_hosts: The targeted nornir hosts after being
    processed through nornir filtering.
    """
    # Execute filter based on hosts in a region
    target_hosts = nr.filter(F(region__eq=region))
    # Print seperator and header
    print("=" * 50)
    print(f"The hosts in region {region} are:")
    # Iterate over filtered results and printout information
    for host, data in target_hosts.inventory.hosts.items():
        print(f"Host: {Fore.CYAN}{host} " + Fore.RESET +
              f"- Region: {Fore.CYAN}{data['region']} " + Fore.RESET +
              f"- Country: {Fore.CYAN}{data['country']} " + Fore.RESET +
              f"- Full Name: {Fore.CYAN}{data['full_name']}")
    # Print total and seperator
    print(f"Total: {len(target_hosts.inventory.hosts.items())}")
    print("=" * 50)
    # Return filtered hosts
    return target_hosts
def filter_production_hosts(nr):
    """
    Filter the hosts inventory, which match the production
    attribute.

    :param nr: An initialised Nornir inventory, used for processing.
    :return target_hosts: The targeted nornir hosts after being
    processed through nornir filtering.
    """
    # Execute filter based on hosts being in production
    target_hosts = nr.filter(F(production__eq=True))
    # Print seperator and header
    print("=" * 50)
    print("The hosts running in Production are:")
    # Iterate over filtered results and printout information
    for host, data in target_hosts.inventory.hosts.items():
        print(f"Host: {Fore.CYAN}{host} " + Fore.RESET +
              f"- Platform: {Fore.CYAN}{data.platform} " + Fore.RESET +
              f"- OS Version: {Fore.CYAN}{data['os_version']} " + Fore.RESET +
              f"- Production?: {Fore.CYAN}{data['production']}")
    # Print total and seperator
    print(f"Total: {len(target_hosts.inventory.hosts.items())}")
    print("=" * 50)
    # Return filtered hosts
    return target_hosts
Esempio n. 15
0
def main():
    nr = InitNornir(config_file="config.yaml")
    filt = F(groups__contains="ios")
    nr = nr.filter(filt)
    print()
    print(nr.inventory.hosts)
    print()
Esempio n. 16
0
def main():
    nr = InitNornir(config_file="config1.yaml", logging={"enabled": False})
    nxos = nr.filter(F(groups__contains="nxos"))
    #import ipdb; ipdb.set_trace()

    render_loopback_result = nxos.run(task=render_loopback)
    print_result(render_loopback_result)
Esempio n. 17
0
def nornir_yml():

    nornir_yml_status = False
    nornir_yml_log = []
    nornir_yml_list = []

    nornir_yml_log.append(('%modules/_nornir_yml','Nornir YAML Query Initialised...', 5))

    if SESSION_TK.debug == 2: # True
        print('\n***DEBUG Nornir YAML SESSION_TK Received:')
        print(pp.pprint(SESSION_TK))

    try:
        nr = InitNornir(config_file='config/nornir_cfg.yaml')

        filter  = nr.filter(F(groups__contains=SESSION_TK.yaml_filter[0]))
        for i in filter.inventory.hosts.keys():
            nornir_yml_list.append(i)

        if SESSION_TK.debug == 2: # True
            print('\n**DEBUG Nornir YAML List Generated:')
            print(pp.pprint(nornir_yml_list))

        nornir_yml_status = True
        nornir_yml_log.append(('%modules/_nornir_yml','Nornir YAML Query Successful', 5))

    except Exception as error:
        nornir_yml_log.append(('%modules/_ise_api','Nornir YAML Query Error: ' + str(error), 4))

    return nornir_yml_status, nornir_yml_log, nornir_yml_list
def check_ping(IP, RACK_NUM, RU_NUM):
     global INTERFACE
     global CORE_SW
     global MAC
     try:
        if IP[0:5] != "10.90":
            print("Mentiond IP is not in range for TY6 DC servers")
        else:
            SWITCH = nr.filter(F(hostname=CORE_SW))
            PING = SWITCH.run(task=netmiko_send_command, command_string="ping {0} count 5".format(IP))
            if "5 packets received" in PING['CS_1'].result or "4 packets received" in PING['CS_1'].result:
                print("Server IP is Pingable")
                ARP = SWITCH.run(task=napalm_get, getters=["arp_table"])
                for cs_name in ARP.keys():
                    CS_NAME = cs_name
                    #print(CS_NAME)

                ARP_LIST = ARP[CS_NAME].result['arp_table']
                for i, j in enumerate(ARP_LIST):
                    ALL_MAC = (j['mac'])
                    ALL_INTERFACE = (j['interface'])
                    ALL_IP = (j['ip'])
                    if ALL_IP == IP:
                       INTERFACE = ALL_INTERFACE.split()[1][1:][:-3]
                       MAC = ALL_MAC
                       check_lacp_lldp(RACK_NUM, RU_NUM)
            else:
                print("Server IP NOT Pingable")
                pass
     except Exception as e:
         print("ERROR:{0}".format(e))
Esempio n. 19
0
def main():
    nr = InitNornir(config_file="config.yaml")
    nr = nr.filter(F(groups__contains="nxos"))
    agg_result = nr.run(task=render_configurations)
    print_result(agg_result)
    agg_result = nr.run(task=write_configurations)
    print_result(agg_result)
Esempio n. 20
0
def main():
    nr = InitNornir(config_file="config.yaml")
    ios_filt = F(groups__contains="ios")
    nr = nr.filter(ios_filt)
    nr.inventory.hosts['cisco3'].password = "******"

    task = nr.run(task=netmiko_send_command,
                  command_string="show ip interface brief")

    print_result(task)
    print("-" * 50)
    print(f"Failed Hosts shwon in task object: {task.failed_hosts}")
    print(f"Failed Hosts shown in nr object: {nr.data.failed_hosts}")
    print("-" * 50)

    print(f"Attempting to recover {nr.data.failed_hosts}")

    # First close the connection to failed hosts and reset the password
    for host in nr.data.failed_hosts:
        try:
            nr.inventory.hosts[host].close_connections()
        except ValueError:
            pass
        nr.inventory.hosts[host].password = os.environ["NORNIR_PASSWORD"]

    recover_task = nr.run(task=netmiko_send_command,
                          on_failed=True,
                          command_string="show ip interface brief")
    print_result(recover_task)
Esempio n. 21
0
def main():

    nr = InitNornir(config_file="config5.yaml", logging={"enabled": False})
    nxos = nr.filter(F(groups__contains="nxos"))
    #import ipdb; ipdb.set_trace()

    render_bgp_result = nxos.run(task=render_bgp_config)
    print_result(render_bgp_result)
    render_intf_result = nxos.run(task=render_intf_config)
    print_result(render_intf_result)

    write_bgp_result = nxos.run(task=write_bgp_config)
    print_result(write_bgp_result)
    write_intf_result = nxos.run(task=write_intf_config)
    print_result(write_intf_result)

    deploy_bgp_result = nxos.run(task=deploy_bgp_config)
    print_result(deploy_bgp_result)
    deploy_intf_result = nxos.run(task=deploy_intf_config)
    print_result(deploy_intf_result)

    print("we now sleep for 10 seconds to ensure BGP processing is done")
    time.sleep(10)

    test_bgp = nxos.run(task=unitest_bgp)
    print_result(test_bgp)
    print(
        "nxos1 bgp peer is UP ====>", test_bgp["nxos1"]
        [1].result["bgp_neighbors"]["global"]["peers"]["172.20.1.2"]["is_up"])
    print(
        "nxos2 bgp peer is UP ====>", test_bgp["nxos2"]
        [1].result["bgp_neighbors"]["global"]["peers"]["172.20.1.1"]["is_up"])
def main():
    """
    Nornir Bonus 2 "BGP Peer Configuration Utility"

    The purpose of this script is to manage all BGP configurations for the NXOS devices.
    This includes prefix lists, route maps and the actual bgp routing configurations. Other config
    items should be left alone. This tool replaces the entire configuration using NAPALM, in order
    to do that safely a configuration checkpoint is taken, and this checkpoint file is copied and
    modified to reflect the desired end state.

    """
    task_list = [
        prepare_interfaces,
        ensure_config_flags,
        get_current_checkpoint,
        render_configurations,
        create_new_checkpoint,
        push_updated_checkpoint,
    ]
    nr = InitNornir(config_file="config.yaml")
    nr = nr.filter(F(groups__contains="nxos"))
    for task in task_list:
        result = nr.run(task=task)
        if any(v.changed for k, v in result.items()):
            print(f">>> Task '{result.name.upper()}' changed...")
        if result.failed:
            print(f">>> Task '{result.name.upper()}' failed... result:")
            print_result(result)
        else:
            print(f">>> Task '{result.name.upper()}' completed successfully!")
Esempio n. 23
0
def check_lacp_lldp(INTERFACE, MAC):
    try:
        # Find the LLDP neighbor IP from which you received the server MAC.
        # Just change the Core switch Management IP for each DC here.
        SWITCH = nr.filter(F(hostname="Put Core switch Management_IP"))
        #SWITCH = nr.filter(F(hostname="Management IP") | F(hostname="Management IP"))
        LACP = SWITCH.run(
            task=netmiko_send_command,
            command_string="show lacp interface {0} | display json | no-more".
            format(INTERFACE))
        LACP_DICT = json.loads(LACP['CS_1'].result)
        LACP_INTERFACE = LACP_DICT["lacp-interface-information-list"][0][
            "lacp-interface-information"][0]["lag-lacp-state"][0]["name"][0][
                "data"]
        LLDP = SWITCH.run(
            task=netmiko_send_command,
            command_string=
            "show lldp neighbors interface {0} | display json | no-more".
            format(LACP_INTERFACE))
        LLDP_DICT = json.loads(LLDP['CS_1'].result)
        LLDP_NEIGHBOR = LLDP_DICT["lldp-neighbors-information"][0][
            "lldp-neighbor-information"][0]["lldp-remote-management-address"][
                0]["data"]
        login_next(MAC, LLDP_NEIGHBOR)
    except Exception as e:
        print("ERROR:{0}".format(e))
Esempio n. 24
0
def main():
    nr = InitNornir(config_file="config.yaml")
    ios_filt = F(groups__contains="ios")
    nr = nr.filter(ios_filt)
    my_results = nr.run(task=netmiko_send_command,
                        command_string="show ip int brief")
    print_result(my_results)
def login_next(MAC,LLDP_NEIGHBOR):
    try:
        print("Connection to TOR: {0}".format(LLDP_NEIGHBOR))
        SWITCH = nr.filter(F(hostname=LLDP_NEIGHBOR))
        MAC_TABLE = SWITCH.run(task=napalm_get, getters=["mac_address_table"])
        for device in SWITCH.inventory.hosts.keys():
            DEVICE = device
            #print(DEVICE)

        MAC_LIST = MAC_TABLE[DEVICE].result['mac_address_table']
        for i, j in enumerate(MAC_LIST):
            ALL_MAC = (j['mac'])
            ALL_INTERFACE = (j['interface'])
            if ALL_MAC == MAC:
               SERVER_INTERFACE = ALL_INTERFACE[:-2]

        INT_INFO = SWITCH.run(task=netmiko_send_command, command_string="show configuration interfaces {0} | display json | no-more".format(SERVER_INTERFACE))
        INT_INFO_DICT = json.loads(INT_INFO[DEVICE].result)
        VLAN_TAG = INT_INFO_DICT["configuration"][0]["interfaces"][0]["interface"][0]["apply-groups"][0]["data"]
        DESC = INT_INFO_DICT["configuration"][0]["interfaces"][0]["interface"][0]["description"][0]["data"]


        print("Server is on device: {0}".format(DEVICE))
        print("Server is on interface: {0}".format(SERVER_INTERFACE))
        print("Server VLAN TAG: {0}".format(VLAN_TAG))
        print("Server RU Number is: {0}".format(DESC))
        print("=======================================================")

    except Exception as e:
        print("ERROR:{0}".format(e))
Esempio n. 26
0
def test_int_qos(nr):
    site = "mv1"
    if site == "mv1":
        site1 = "mv1"
        site2 = "mv3"
    else:
        site1 = "mv2"
        site2 = "mv2"
    hosts = nr.filter(
        F(role='internet-access') & F(site=site1)
        | F(role='internet-access') & F(site=site2))
    hosts.run(task=config_backup)
    qos = []
    for host in hosts.inventory.hosts.values():
        qos.append(sorted(host['qos'], key=itemgetter("class")))
    assert qos[0] == qos[1]
Esempio n. 27
0
def main():
    nr = InitNornir(config_file="config.yaml")
    nr = nr.filter(F(groups__contains="eos"))
    for hostname, host_obj in nr.inventory.hosts.items():
        host_obj.password = PASSWORD
    nr.run(task=networking.netmiko_send_command,
           command_string="show mac address-table")
Esempio n. 28
0
def main():
    # check arguments
    opt = check_options()

    devices = InitNornir(config_file="config.yaml")
    filt_dev = devices.filter(
        F(groups__any=opt.type))  # to test : & or |  F(customer=opt.customer)

    # credentials input ... assumes you have adequate groups in groups.yaml file
    for platf in opt.type:
        try:
            devices.inventory.groups[platf].username = input(
                f'Enter {platf} username : '******'Enter {platf} user password: '******'Enter {platf} enable password: ')
        except (TypeError, KeyError):
            print(
                "Error populating credentials, verify if adequate groups are in your groups.yaml file"
            )

    print("calling task ...")
    filt_dev.run(name="Get command", task=get_command, opt=opt)
    print("DONE.")

    return
Esempio n. 29
0
def main():
    nr = InitNornir(config_file="config.yaml")

    nxos_group = nr.filter(F(groups__contains="nxos"))
    nxos_hosts = nxos_group.inventory.hosts
    #print(nxos_hosts)

    results = nxos_group.run(task=napalm_get,
                             getters=['config', 'facts'],
                             getters_options={'config': {
                                 'retrieve': 'all'
                             }})
    #print_result(results)

    d = {}
    for nxos in nxos_hosts:
        d[nxos] = {}

        model = results[nxos][0].result['facts']['model']
        #pp(model)
        uptime = results[nxos][0].result['facts']['uptime']
        #pp(uptime)
        vendor = results[nxos][0].result['facts']['vendor']
        #pp(vendor)
        running = results[nxos][0].result['config']['running'].splitlines()[5:]
        startup = results[nxos][0].result['config']['startup'].splitlines()[5:]
        #pp(running)
        #pp(startup)
        diff = (running == startup)

        d[nxos]['start_running_match'] = diff
        d[nxos]['model'] = model
        d[nxos]['uptime'] = uptime
        d[nxos]['vendor'] = vendor
    pp(d)
def filter_neq_site_code(nr, site_code):
    """
    Filter the hosts inventory, based on not equalling a site code.

    :param nr: An initialised Nornir inventory, used for processing.
    :param site_code: The site code to not filter on.
    :type site_code: string

    :return target_hosts: The targeted nornir hosts after being
    processed through nornir filtering.
    """
    # Execute filter based on devices not equal to the site code
    target_hosts = nr.filter(~F(site_code__eq=site_code))
    # Print seperator and header
    print("=" * 50)
    print(f"The hosts WITHOUT site code - {site_code} are:")
    # Iterate over filtered results and printout information
    for host, data in target_hosts.inventory.hosts.items():
        print(f"Host: {Fore.CYAN}{host} " + Fore.RESET +
              f"- Site Code: {Fore.CYAN}{data['site_code']}")
    # Print total and seperator
    print(f"Total: {len(target_hosts.inventory.hosts.items())}")
    print("=" * 50)
    # Return filtered hosts
    return target_hosts