def main(): nr = InitNornir(host_file='hosts.yaml', group_file='groups.yaml', num_workers=20) test = nr.filter(site='test') result = test.run(load_data) print_result(result)
def main(): testing_ok = True nr = InitNornir(host_file='hosts.yaml', group_file='groups.yaml', num_workers=20) test = nr.filter(site='test') result = test.run(task=napalm_get, getters=['get_lldp_neighbors']) # Checking LLDP neighbors for device_name, device_output in result.items(): if device_name == 'R1-test': if device_output[0].result['get_lldp_neighbors']['Ethernet0/0'][0][ 'hostname'] != 'R2.test.example.com': logging.error( 'failed to get right neighbors on {}'.format(device_name)) testing_ok = False if device_name == 'R2-test': if device_output[0].result['get_lldp_neighbors']['Ethernet0/0'][0][ 'hostname'] != 'R1.test.example.com': logging.error( 'failed to get right neighbors on {}'.format(device_name)) testing_ok = False if not testing_ok: sys.exit(1)
def main(): # Initialize Nornir object using hosts.yaml and groups.yaml norn = InitNornir(config_file="nornir.yml") nornir_set_creds(norn) print("Transferring files") result = norn.run( task=os_upgrade, num_workers=20, ) std_print(result) # Filter to only a single device norn_ios = norn.filter(hostname="cisco1.twb-tech.com") aggr_result = norn_ios.run(task=set_boot_var) # If setting the boot variable failed (assumes single device at this point) for hostname, val in aggr_result.items(): if val[0].result is False: sys.exit("Setting the boot variable failed") # Verify the boot variable result = norn_ios.run( netmiko_send_command, command_string="show run | section boot", num_workers=20, ) std_print(result) continue_func()
def main(): # Initialize Nornir object using default "SimpleInventory" plugin nr = InitNornir() nornir_set_creds(nr) result = nr.run( task=os_upgrade, num_workers=20, ) std_print(result)
def main(): # Initialize Nornir object using hosts.yaml and groups.yaml norn = InitNornir(config_file="nornir.yml") nornir_set_creds(norn) print("Transferring files") result = norn.run( task=os_upgrade, num_workers=20, ) std_print(result) # Filter to only a single device norn_ios = norn.filter(hostname="cisco1.twb-tech.com") aggr_result = norn_ios.run(task=set_boot_var) # If setting the boot variable failed (assumes single device at this point) for hostname, val in aggr_result.items(): if val[0].result is False: sys.exit("Setting the boot variable failed") # Verify the boot variable result = norn_ios.run( netmiko_send_command, command_string="show run | section boot", num_workers=20, ) std_print(result) continue_func() # Save the config result = norn_ios.run( netmiko_send_command, command_string="write mem", ) std_print(result) # Reload continue_func(msg="Do you want to reload the device (y/n)? ") result = norn_ios.run( netmiko_send_command, use_timing=True, command_string="reload", ) # Confirm the reload (if 'confirm' is in the output) for device_name, multi_result in result.items(): if 'confirm' in multi_result[0].result: result = norn_ios.run( netmiko_send_command, use_timing=True, command_string="y", ) print("Devices reloaded")
def main(): # Initialize Nornir object using hosts.yaml and groups.yaml norn = InitNornir(config_file="nornir.yml") nornir_set_creds(norn) result = norn.run( task=os_upgrade, num_workers=20, ) std_print(result)
def send_napalm_commands(cmds, show_output=False, debug=False): """ For a given list of commands, cmds, execute the napalm_cli method via Nornir Task and return a dictionary of dictionaries First key = device Secondary key(s) = show commands executed via cmds show_output is an optional argument which prints out the Ansible-like run output. debug is an optional argument which prints out values to assist in debugging. :param cmds: list of commands to execute on each device :param show_output: Boolean which defaults to False. When True values the Ansible-like run output will be printed to stdout :param debug: Boolean which defaults to False. When True values will be printed to stdout :return: output_dict """ output_dict = {} if isinstance(cmds, list): nornir_instance = InitNornir(dry_run=True) cli_result = nornir_instance.run(napalm_cli, commands=cmds) # Our goal is to build a dictionary of dictionaries # so that it can be referenced a bit more simply as output_dict[device1][showcmd1] # Iterate over the first set of keys in the results object which will represent each device for dev_key in cli_result.keys(): # Iterate over one or more results keys which represent the show command or show commands # extracted from each device # Alternatively we could use the cmds list to build the inside dict # but just in case something goes wrong, lets build it from the actual keys if debug: print(cli_result[dev_key][0].result.keys()) for result_key in cli_result[dev_key][0].result.keys(): output_dict.update( {dev_key: cli_result[dev_key][0].result[result_key]}) if debug: for k, v in output_dict.items(): print("device: {} \toutput: {}".format(k, v)) else: print( "ERROR! argument passed to function must be a list! Will return empty dictionary." ) if show_output: print_result(cli_result, vars=['stdout']) return output_dict
def main(): # Initialize Nornir object using hosts.yaml and groups.yaml brg = InitNornir(config_file="nornir.yml") nornir_set_creds(brg) test_file = 'test_file9.txt' result = brg.run( task=os_upgrade, num_workers=20, ) std_print(result)
def main(): # Initialize Nornir object using hosts.yaml and groups.yaml brg = InitNornir(config_file="nornir.yml") nornir_set_creds(brg) print("Transferring files") result = brg.run( task=os_upgrade, num_workers=20, ) std_print(result) # Filter to only a single device brg_ios = brg.filter(hostname="cisco1.twb-tech.com") # Verify the boot variable result = brg_ios.run( netmiko_send_command, command_string="show run | section boot", num_workers=20, ) std_print(result) continue_func() # Save the config result = brg_ios.run( netmiko_send_command, command_string="write mem", num_workers=20, ) std_print(result) # Reload continue_func(msg="Do you want to reload the device (y/n)? ") result = brg_ios.run( netmiko_send_command, use_timing=True, command_string="reload", num_workers=1, ) # Confirm the reload (if 'confirm' is in the output) for device_name, multi_result in result.items(): if 'confirm' in multi_result[0].result: result = brg_ios.run( netmiko_send_command, use_timing=True, command_string="y", ) print("Devices reloaded")
def main(): # Get our shov vlan output from each device in our inventory send_commands = ['show vlan'] output_dict = nornir_discovery.send_napalm_commands(send_commands, show_output=True, debug=False) # Set the TextFSM template we will be using to parse the show vlan output so we get it back in a way we can use template_filename = 'cisco_ios_show_vlan.template' # Initialize the vlan dictionary we will send to our Jinja2 template j2_data_dict = {} # ======= Define the Nornir Environment ======== nornir_instance = InitNornir() # For each device lets build out the list of vlans which must be removed for dev, output in output_dict.items(): parsed_results = nornir_discovery.parse_with_texfsm(output, template_filename, debug=False) remove_vlan_list = [] # For each Vlan we found configured on the device for vlan_data in parsed_results: # We are only interested in vlans between 1 and 999 # vlan_data[0] is the vlan number if 1 < int(vlan_data[0]) < 1000: ints_in_vlan = len(vlan_data[3]) # If the vlan has no associated interfaces, the add it to the remove_vlan_list list if ints_in_vlan == 0: remove_vlan_list.append(vlan_data[0]) # Build a dictionary where the key is the device or host and the value the list of vlans to remove # This will be passed along when we build our configs j2_data_dict.update({dev: remove_vlan_list}) # ====== Generate Configs # Execute a task "run" in the Nornir environment using our config_file Task function and pass it the customized data # which is required to build out a custom config for each device removing any unused vlans and adding the standard # vlans r = nornir_instance.run(task=config_to_file, arg=j2_data_dict) print("\n") # Prints abbreviated output print_result(r, vars=['stdout'])
def test_InitNornir_combined(self): brg = InitNornir(config_file=os.path.join(dir_path, "a_config.yaml"), num_workers=200) assert not brg.dry_run assert brg.config.num_workers == 200 assert len(brg.inventory.hosts) assert len(brg.inventory.groups)
def main(config, getters, debug): nr = InitNornir( config_file=config, dry_run=False, num_workers=1 if debug else 20, ) result = nr.run( name="Retrieving facts from the device", task=napalm_get, getters=getters, ) print_result( result, severity_level=logging.DEBUG if debug else logging.INFO, ) return result
def test_InitNornir_different_transform_function_imported(self): brg = InitNornir( config_file=os.path.join(dir_path, "a_config.yaml"), transform_function=transform_func, ) for value in brg.inventory.hosts.values(): assert value.processed_by_transform_function
def test_InitNornir_different_transform_function_by_string(self): nr = InitNornir( config_file=os.path.join(dir_path, "a_config.yaml"), transform_function="tests.core.test_InitNornir.transform_func", ) for value in nr.inventory.hosts.values(): assert value.processed_by_transform_function
def main(config, path, debug): nr = InitNornir( config_file=config, dry_run=False, num_workers=1 if debug else 20, ) result = nr.run( name="Backup configuration of devices", task=backup, path=path, ) print_result( result, severity_level=logging.DEBUG if debug else logging.INFO, ) return result
def main() -> None: args = parse_arguments() nr = InitNornir("config.yaml") update_host_vars(nr.inventory) update_description(nr.inventory) deployment = Deployment(args.topologies, nr.inventory) import ipdb ipdb.set_trace()
def main() -> None: nr = InitNornir("config.yaml") matrix_switches = nr.inventory.filter(F(has_parent_group="matrix-switches")) update_host_vars(matrix_switches) deployment = load_current_deployment("2_mixed") topologies = load_topologies() update_matrix(nr.inventory, topologies, deployment) breakpoint()
def test_InitNornir_defaults(self): os.chdir("tests/inventory_data/") try: brg = InitNornir() finally: os.chdir("../../") assert not brg.dry_run assert brg.config.num_workers == 20 assert len(brg.inventory.hosts) assert len(brg.inventory.groups)
def main(): nornir_runner = InitNornir(config_file="config-ansible.yaml") inventory = nornir_runner.inventory # for host in inventory.hosts.values(): # print(host.items()) # print(nornir_runner.inventory.hosts.items()) nornir_runner.filter(filter_func=lambda x: x.get("site") == "sj" or x.get("country") == 'us').inventory.hosts.keys() servers = nornir_runner.filter(role="server") result = servers.run(task=commands.remote_command, command="whoami ; python -V") print_result(result) result = servers.run(task=apis.http_method, url="http://localhost:3080/v2/computes") print_result(result) # sj_edge = nornir_runner.filter(site="sj") # result = sj_edge.run(task=networking.napalm_get, name="Collecting facts using NAPALM", getters=["facts"]) # print_result(result) # # result = sj_edge.run(task=basic_configuration, name="Compiling and applying configuration") # print_result(result) sj_br1 = nornir_runner.filter(name="sj-br1") result = sj_br1.run(task=networking.netmiko_file_transfer, name="send file using Netmiko", source_file="config-ansible.yaml", dest_file="config-ansible.yaml") print_result(result)
def test_InitNornir_programmatically(self): brg = InitNornir( num_workers=100, inventory="nornir.plugins.inventory.simple.SimpleInventory", SimpleInventory={ "host_file": "tests/inventory_data/hosts.yaml", "group_file": "tests/inventory_data/groups.yaml", }, ) assert not brg.dry_run assert brg.config.num_workers == 100 assert len(brg.inventory.hosts) assert len(brg.inventory.groups)
def main(): dataFile = 'expected-NOR.yml' # expected results or new file to write results currentFile = 'current-NOR.yml' # current read nr = InitNornir(logging_loggers=['nornir', '__main__']) command = 'show cdp neighbors' logger.info("RUNNING COMMAND %s" % command) start = time.time() result = nr.run(task=netmiko_send_command, command_string=command, use_textfsm=True) end = time.time() logger.info("COMMANDS RUN IN %s", str(round(end - start, 1))) # convert nornir output to dictionary current = {} for key in result: current[key] = result[key][0].result expected = readExpected(dataFile) if not expected: # if dataFile is missing write current read to dataFile with open(dataFile, 'w') as dF: yaml.dump(current, dF, default_flow_style=False) dF.close() logger.info("EXISTING DATA MISSING - WRITTEN CURRENT TO FILE %s" % dataFile) print("EXISTING DATA MISSING - WRITTEN CURRENT TO FILE %s" % dataFile) else: # if a dataFile is present proceed with compare with open(currentFile, 'w') as dF: yaml.dump(current, dF, default_flow_style=False) dF.close() logger.info("WRITTEN CURRENT TO FILE %s" % currentFile) compareTopology(current, expected, nr) end = time.time() logger.info("TOTAL RUNTIME %s", str(round(end - start, 1)))
def main(): nr = InitNornir(host_file='hosts.yaml', group_file='groups.yaml', num_workers=20) test = nr.filter(site='test') result = test.run(task=napalm_get, getters=['get_config']) # Store startup configurations for device_name, device_output in result.items(): f = open('configs/{}.cfg'.format(device_name), 'w') f.write(clean_config(device_output[0].result['get_config']['startup'])) f.close() # Store templates templates = [] for device_name, device_output in result.items(): template_name = device_name.split('-')[0] if template_name not in templates: f = open('configs/{}-test.template'.format(template_name), 'w') f.write( config_to_template( device_output[0].result['get_config']['startup'])) f.close() templates.append(template_name)
#!/usr/bin/env python from nornir.core import InitNornir from nornir.plugins.functions.text import print_result from nornir.plugins.tasks.networking import napalm_get # Initialize nornir nr = InitNornir( config_file="/nornir/nornir.yaml", dry_run=True, num_workers=20 ) # Let's just filter the hosts we want to operate on cmh = nr.filter(type="network_device") # Let's retrieve the information and print them on screen results = cmh.run( task=napalm_get, getters=["facts", "interfaces"] ) print_result(results)
def test_InitNornir_file(self): nr = InitNornir(config_file=os.path.join(dir_path, "a_config.yaml")) assert not nr.dry_run assert nr.config.num_workers == 100 assert len(nr.inventory.hosts) assert len(nr.inventory.groups)
from nornir.core import InitNornir from nornir.plugins.tasks.networking import napalm_get from nornir.plugins.functions.text import print_result nr = InitNornir() result = nr.run( napalm_get, getters=['get_facts', 'get_config',]) print_result(result)
# -*- coding: utf-8 -*- """ Created on Wed Feb 6 13:04:03 2019 @author: Synophic """ from nornir.core import InitNornir from nornir.plugins.tasks.networking import netmiko_send_command from nornir.plugins.functions.text import print_result commands = input("Enter Commands: ") cmds = commands.split(",") for cmd in cmds: nr = InitNornir() result = nr.run(task=netmiko_send_command, command_string=cmd) print_result(result)
from nornir.core import InitNornir from nornir.plugins.tasks.networking import netmiko_send_config from nornir.plugins.functions.text import print_result target = input("Pick group of devices to configure core, distribution, access: ") cfgs = input("Enter configuration lines seperated by ',': ") cfgs_items = cfgs.split(",") print(cfgs_items) nr = InitNornir() target_host = nr.filter(site=target) result = target_host.run( task=netmiko_send_config, config_commands=cfgs_items ) print_result(result)
def test_InitNornir_different_inventory_imported(self): brg = InitNornir( config_file=os.path.join(dir_path, "a_config.yaml"), inventory=StringInventory, ) assert isinstance(brg.inventory, StringInventory)
def test_InitNornir_different_inventory_by_string(self): brg = InitNornir( config_file=os.path.join(dir_path, "a_config.yaml"), inventory="tests.core.test_InitNornir.StringInventory", ) assert isinstance(brg.inventory, StringInventory)
from nornir.core import InitNornir from nornir.plugins.functions.text import print_result from nornir.plugins.tasks import networking nr = InitNornir(config_file="config.yaml") lab_hosts = nr.filter(site="lab", role="spline") result = lab_hosts.run(task=networking.napalm_get, getters=["facts", "config", "interfaces_ip"]) print_result(result) print(nr.inventory.hosts) print(nr.inventory.groups)