def configuring_interfaces(self):
        rendered = self.render_template("interfaces.j2")
        for name, config in rendered.items():
            self.to_local_file(f"interfaces-{name}", config)

        hosts = self._nornir.filter(
            F(role="servers") | F(role="spine") | F(role="leaf")
        )
        res = hosts.run(
            task=self.copy_files,
            src_file="./resources/interfaces",
            dst_file="/tmp/interfaces",
        )
        print_result(res)
        hosts.run(
            task=self.run_remote_cmd,
            cmd="sudo cp /tmp/interfaces /etc/network/interfaces",
        )
Beispiel #2
0
    def test_filtering_string_in_list(self, nornir):
        f = F(platform__in=["linux", "mock"])
        filtered = sorted(list((nornir.inventory.filter(f).hosts.keys())))

        assert filtered == [
            "dev3.group_2",
            "dev4.group_2",
            "dev5.no_group",
            "dev6.group_3",
        ]
Beispiel #3
0
    def test_filtering_by_callable_has_parent_group(self, nornir):
        f = F(has_parent_group="parent_group")
        filtered = sorted(list((nornir.inventory.filter(f).hosts.keys())))

        assert filtered == [
            "dev1.group_1",
            "dev2.group_1",
            "dev4.group_2",
            "dev6.group_3",
        ]
Beispiel #4
0
def remove_ex2_flash_files():
    # prep to ensure test files do not exist on devices
    nornir_inventory = gen_inventory_dict("~/nornir_inventory/")
    nr = InitNornir(inventory=nornir_inventory, logging=NORNIR_LOGGING)
    eos = nr.filter(F(groups__contains="eos"))

    # remove test files from eos flash
    eos.run(task=netmiko_send_command, command_string="terminal dont-ask")
    eos.run(task=netmiko_send_command,
            command_string="delete flash:arista_zzzzz.txt")
Beispiel #5
0
def main():
    nr = InitNornir(config_file="config.yaml")
    nr = nr.filter(F(groups__contains="nxos"))
    for host, data in nr.inventory.hosts.items():
        data.password = PASSWORD
    nr.run(
        task=networking.netmiko_send_command,
        command_string="show mac address-table",
        num_workers=1,
    )
Beispiel #6
0
    def test_negate(self, nornir):
        f = ~F(groups__contains="group_1")
        filtered = sorted(list((nornir.inventory.filter(f).hosts.keys())))

        assert filtered == [
            "dev3.group_2",
            "dev4.group_2",
            "dev5.no_group",
            "dev6.group_3",
        ]
Beispiel #7
0
def main():
    norn = InitNornir(config_file="./nornir.yml")

    f = F(groups__contains="ios")
    napalm_hosts = norn.filter(f)

    result = napalm_hosts.run(task=napalm_get, getters=["facts"])

    std_print(result)

    netmiko_hosts = norn.filter(F(groups__contains="nxos"))
    result = netmiko_hosts.run(
        netmiko_send_command,
        num_workers=60,
        command_string="show lldp neighbors",
        use_textfsm=True,
    )

    std_print(result)
Beispiel #8
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)
    agg_result = nr.run(task=deploy_configurations)
    print_result(agg_result)
    nr.run(task=validate_bgp)
def test_krk_vlans(nr):
    config = load_config(CONFIG_FILE)
    hosts = nr.filter(F(groups__contains=config["group"]))
    hosts.run(task=get_data, config=config)

    desired_vlans = config["data"]["vlans"]

    for host in hosts.inventory.hosts.values():
        configured_vlans = host["vlans"]
        assert configured_vlans == desired_vlans, f"Failed for host: {host.name}"
Beispiel #10
0
def main():
    LOGGER.info("Script initalizing...")
    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
    LOGGER.critical("Passwords set, commence automation!")
    nr.run(task=netmiko_send_command, command_string="show mac address-table")
    LOGGER.error("Oh no! We're all out of automation tasks :(")
    LOGGER.debug("Hey, what are you still doing here?")
Beispiel #11
0
    def test_nested_data_a_dict_doesnt_contain(self, nornir):
        f = ~F(nested_data__a_dict__contains="a")
        filtered = sorted(list((nornir.inventory.filter(f).hosts.keys())))

        assert filtered == [
            "dev2.group_1",
            "dev3.group_2",
            "dev4.group_2",
            "dev5.no_group",
        ]
Beispiel #12
0
def main(filt):

    nr = InitNornir(config_file='config.yaml')

    if len(filt) > 1:
        filter_what, filter_for = filt[0], filt[1:]
        f = F(**{f'{filter_what}__any': filter_for})
        nr = nr.filter(f)

    print(nr.inventory.hosts)
Beispiel #13
0
def main():
    nr = InitNornir(config_file="config.yaml")
    nr = nr.filter(F(groups__contains="iosv"))
    print(
        'Running iosstaging.py against the following Nornir inventory hosts:',
        nr.inventory.hosts.keys())
    nornir_set_creds(nr)
    print("Starting Image Transfer")
    result = nr.run(task=os_staging)
    print_result(result)
Beispiel #14
0
def main():
    nr = InitNornir(config_file="config.yaml")
    #Filter devices to run against
    nr = nr.filter(F(groups__contains="iosv"))
    print('Running postvalidaiton.py against the following Nornir inventory hosts:', nr.inventory.hosts.keys())
    # Ask for credentials at runtime instead of storing.
    nornir_set_creds(nr)

    print("Collecting running configurations and operational values\n")
    resultconf = nr.run(task=collect_configs)
    resultgetters = nr.run(task=collect_getters)
    #import ipdb; ipdb.set_trace()

    #Loop through napalm getters and output current running version.
    prYellow('Current IOS Running Versions:')
    for host in resultgetters:
        print(host, '>>', resultgetters[host][1].result['facts']['os_version'])

    #Perform a Diff between the pre and post nornir getter files we saved.
    for host in nr.inventory.hosts:
        #dont try to open files or compare if a host failed collection
        if host in resultconf.failed_hosts or host in resultgetters.failed_hosts:
            print('!', host, 'failed collection and Op State will not be compared\n')
            #TODO: log netmiko/nornir error to file. otherwise it should exist in nornir.log.
            continue
        else:
            #load facts in hosts pre and post folder and store to var. since were not using pyats native learn objects we must loop through files
            prGreen("vvv --- " + host + " --- Begin Comparison between Pre Upgrade and Post Upgrade operational values vvv")
            for filename in os.listdir(initial_facts_dir+host):
                with open(initial_facts_dir+host+'/'+filename, 'r') as f:
                    initialstate = json.load(f)
                with open(facts_dir+host+'/'+filename, 'r') as f:
                    poststate = json.load(f)
                compare = Diff(initialstate, poststate)
                compare.findDiff()
                print('#', filename, '#\n', compare)
            prGreen("^^^ --- " + host + " --- End Comparison between Pre Upgrade and Post Upgrade operational values ^^^\n")


            prGreen("vvv --- " + host + " --- Begin Comparison between Pre Upgrade and Post Upgrade configurations vvv")
            with open(initial_config_dir+host+'-running.cfg', 'r') as f:
                cfg = f.read()
            initialconfig = Config(cfg)
            initialconfig.tree()
            with open(config_dir+host+'-running.cfg', 'r') as f:
                cfg = f.read()
            postconfig = Config(cfg)
            postconfig.tree()
            compare = Diff(initialconfig, postconfig)
            compare.findDiff()
            prCyan("# " + os.path.basename(f.name) + " #")
            print(compare)
            #ipdb.set_trace()
            prGreen("^^^ --- " + host + " --- End Comparison between Pre Upgrade and Post Upgrade configurations ^^^\n")
Beispiel #15
0
def main():
    nr = InitNornir(config_file="../config.yaml")
    devices = nr.filter(F(platform="junos"))
    # import ipdb

    # ipdb.set_trace()
    result = devices.run(
        task=networking.napalm_validate,
        src="../validators/validate.yaml",
    )
    print_result(result)
Beispiel #16
0
def main():
    client_access_devices = nr.filter(F(device_role__name="Access"))
    client_distribution_devices = nr.filter(
        F(device_role__name="Distribution"))
    client_core_devices = nr.filter(F(device_role__name="Core"))
    access_task = client_access_devices.run(task=verify_vlan)
    print_result(access_task)
    distribution_task = client_distribution_devices.run(task=verify_vlan)
    print_result(distribution_task)
    core_task = client_core_devices.run(task=verify_vlan)
    print_result(core_task)
    client_access_devices.run(task=config_rollback,
                              on_failed=True,
                              on_good=False)
    client_core_devices.run(task=config_rollback,
                            on_failed=True,
                            on_good=False)
    client_distribution_devices.run(task=rollback_configuration,
                                    on_failed=True,
                                    on_good=False)
Beispiel #17
0
 def setup(self) -> None:
     """
     Sets up the all destinations to act as iperf servers.
     """
     test_data = self.nuts_parameters["test_data"]
     destinations = F(
         hostname__any={entry["destination"]
                        for entry in test_data})
     assert self.nornir is not None
     selected_destinations = self.nornir.filter(destinations)
     selected_destinations.run(task=self.server_setup)
Beispiel #18
0
 def teardown(self) -> None:
     """
     Stops all destinations that acted as iperf servers.
     """
     test_data = self.nuts_parameters["test_data"]
     destinations = F(
         hostname__any={entry["destination"]
                        for entry in test_data})
     assert self.nornir is not None
     selected_destinations = self.nornir.filter(destinations)
     selected_destinations.run(task=self.server_teardown)
Beispiel #19
0
def main():
    nr = InitNornir(config_file="config.yaml")
    filt = F(groups__contains="ios")
    nr = nr.filter(filt)
    my_results = nr.run(task=netmiko_send_command,
                        command_string="show run | inc hostname")
    print()
    print(type(my_results))
    print(my_results.keys())
    print(my_results.items())
    print(my_results.values())
def main():
    nr = InitNornir(config_file="config.yaml")
    nr = nr.filter(F(groups__contains="nxos"))
    agg_result = nr.run(
        task=napalm_get,
        getters=["config", "facts"],
        getters_options={"config": {
            "retrieve": "running"
        }},
    )
    print_result(agg_result)
Beispiel #21
0
def inventory_selector(
        nr: Nornir,
        resync: bool = True,
        hostname: Optional[str] = None,
        device_type: Optional[str] = None,
        group: Optional[str] = None) -> Tuple[Nornir, int, List[str]]:
    """Return a filtered Nornir inventory with only the selected devices

    Args:
        nr: Nornir object
        resync: Set to false if you want to filter out devices that are synchronized
        hostname: Select device by hostname (string)
        device_type: Select device by device_type (string)
        group: Select device by group (string)

    Returns:
        Tuple with: filtered Nornir inventory, total device count selected,
                    list of hostnames that was skipped because of resync=False
    """
    skipped_devices = []
    if hostname:
        nr_filtered = nr.filter(name=hostname).filter(managed=True)
    elif device_type:
        nr_filtered = nr.filter(F(groups__contains='T_' +
                                  device_type)).filter(managed=True)
    elif group:
        nr_filtered = nr.filter(F(groups__contains=group)).filter(managed=True)
    else:
        # all devices
        nr_filtered = nr.filter(managed=True)

    if resync or hostname:
        return nr_filtered, len(nr_filtered.inventory.hosts), skipped_devices
    else:
        pre_device_list = list(nr_filtered.inventory.hosts.keys())
        nr_filtered = nr_filtered.filter(synchronized=False)
        post_device_list = list(nr_filtered.inventory.hosts.keys())
        skipped_devices = [
            x for x in pre_device_list if x not in post_device_list
        ]
        return nr_filtered, len(post_device_list), skipped_devices
Beispiel #22
0
def main():
    nr = InitNornir(config_file="config.yaml")
    open("non_compliant_devices", "w").close()
    print("\n"+"**********"+"[u cyan]Welcome to Network Audit Script[/u cyan]"+"**********"+"\n\n")

    dev_role = click.prompt(click.style("Enter device type for audit:", fg='yellow'),
            type=click.Choice(['TOR', 'corerouter', 'coreswitch', 'all'],
                case_sensitive=True))
    command = click.prompt(click.style("Enter the desired command ", fg='bright_magenta'))
    find_string = click.prompt(click.style("Enter string or list of comma seperated strings to be matched", fg='bright_blue')).split(',')

    print(50*"#")
    if dev_role == "all":
        junos = nr.filter(F(platform="junos"))
        out = junos.run(task=audit, command=command, find_string=find_string)
        print(50*"#")
    else:
        junos = nr.filter(F(role="{0}".format(dev_role)))
        out = junos.run(task=audit, command=command, find_string=find_string)
        print(50*"#")
    print_result(out)
Beispiel #23
0
def main():
    nr = InitNornir(config_file="config.yaml")
    ios_filt = F(groups__contains="ios")
    eos_filt = F(groups__contains="eos")
    nr = nr.filter(ios_filt | eos_filt)

    my_results = nr.run(task=napalm_get, getters=["arp_table"])
    parsed_results = []
    for host, multiresult in my_results.items():
        output = multiresult[0].result["arp_table"]
        desired_data = ""
        for entry in output:
            if entry["ip"] == GATEWAY:
                desired_data = entry
                break
        parsed_results.append((host, desired_data))

    print()
    for host, gw_data in parsed_results:
        print(f"Host: {host}, Gateway: {gw_data}")
    print()
def check_lacp_lldp(INTERFACE,MAC):
     try:
       SWITCH = nr.filter(F(hostname="10.91.2.4"))
       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))
Beispiel #25
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()
    for host in results:
        print("-" * 80)
        print(host)
        pprint(results[host].result)
        print("-" * 80)
Beispiel #26
0
def main():
    nr = InitNornir(config_file="config.yaml")
    devices = nr.filter(F(platform="junos"))
    # import ipdb

    # ipdb.set_trace()
    result = devices.run(
        task=networking.napalm_validate,
        src="validate_ipaddr.yaml",
    )
    # result = devices.run(task=networking.napalm_cli, commands=["show version"])
    print_result(result)
Beispiel #27
0
def run_interfaces_config(device, group):
    # config_file = os.environ.get('NORNIR_CONFIG_FILE')
    # os.chdir('../')
    # os.getcwd()
    # breakpoint()
    nr = InitNornir(config_file=f"{config_file}")
    if device:
        nr = nr.filter(name=f"{device}")
    if group:
        nr = nr.filter(F(groups__contains=f"{group}"))
    result = nr.run(task=interfaces_config)
    print_result(result)
Beispiel #28
0
def main():
    nr = InitNornir(config_file="config.yaml")
    filt = F(groups__contains="ios")
    nr = nr.filter(filt)
    my_results = nr.run(task=netmiko_send_command,
                        command_string="show run | inc hostname")
    host_results = my_results["cisco3"]
    print()
    print(f"host_results is of type: {type(host_results)}")
    print(f"Zeroith element in host_results is: {repr(host_results[0])}")
    print(f"Zeroith element in host_results is: {host_results[0]}")
    print(f"Is host_results interable? {host_results.__iter__}")
Beispiel #29
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 = "******"
    my_results = nr.run(task=netmiko_send_command,
                        command_string="show ip int brief")
    print_result(my_results)
    print()
    print(f"Task failed hosts: {my_results.failed_hosts}")
    print(f"Global failed hosts: {nr.data.failed_hosts}")
    print()
Beispiel #30
0
def main():
    nr = InitNornir(config_file="config.yaml")
    nxos = nr.filter(F(platform="nxos"))
    results = nxos.run(task=napalm_get,
                       getters="config",
                       getters_options={"config": {
                           "retrieve": "running"
                       }})
    for host, multi in results.items():
        print("=" * 80)
        print(f"Device {host}")
        pprint(multi[0].result)