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) # Filter to only a single device nr_ios = nr.filter(hostname="cisco1.domain.com") aggr_result = nr_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 = nr_ios.run( task=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) # Filter to only a single device nr_ios = nr.filter(hostname="cisco1.domain.com") aggr_result = nr_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 = nr_ios.run( task=netmiko_send_command, command_string="show run | section boot", num_workers=20, ) std_print(result) continue_func() # Save the config result = nr_ios.run( task=netmiko_send_command, command_string="write mem", ) std_print(result) # Reload continue_func(msg="Do you want to reload the device (y/n)? ") result = nr_ios.run( task=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 = nr_ios.run( task=netmiko_send_command, use_timing=True, command_string="y", ) print("Devices reloaded")
from nornir import InitNornir nr = InitNornir(config_file="config.yaml") from nornir.plugins.tasks import commands from nornir.plugins.functions.text import print_result from nornir.plugins.tasks import networking giga_core = nr.filter(site="giga") result = giga_core.run(task=networking.napalm_get, getters=["config"], retrieve="all") print_result(result)
from nornir import InitNornir from nornir_netmiko import netmiko_send_command from nornir_utils.plugins.functions import print_result nr = InitNornir(config_file="config.yaml") #sw4 = nr.filter(filter_func=lambda host: host.name== 'sw4') switches = ['192.168.2.11', '192.168.2.12', '192.168.2.13'] sw1_sw2_sw3 = nr.filter(filter_func=lambda host: host.hostname in switches) results = sw1_sw2_sw3.run(netmiko_send_command, command_string='sh ip arp') print_result(results)
#pp.pprint(json.dumps(doc2)) #with open(f"host_vars/router/{task.host}.xml") as f: # f.write(fin) #tree=ET.parse(f"host_vars/{task.host}.xml") #root=tree.getroot() #print(root) #print(root.tag) #for elem in root: #print(elem.tag, elem.attrib) #print(ET.tostring(elem, encoding="utf8").decode("utf8")) #test = ET.tostring(elem, encoding="utf8").decode("utf8") #for subelem in elem: #test = ET.tostring(subelem, encoding="utf8").decode("utf8") #print(test) #print(subelem.tag, subelem.attrib) #for subsub in subelem: #print(subsub.tag, subsub.attrib) #for s in subsub: #print(s.tag, s.attrib) #task.run(task=write_file, content=test, filename=f"host_vars/router/{task.host}.xml") # print(ET.tostring(root, encoding="utf8").decode("utf8")) #task.run(task=write_file, content=doc, filename=f"host_vars/router/{task.host}.xml") return result spine = nr.filter(F(groups__contains="spine")) result = spine.run(task=yang_sucks) print_result(result)
def main(): nr = InitNornir() nr = nr.filter(F(groups__contains="sea") | F(groups__contains="sfo")) print(nr.inventory.hosts)
inputsite = input("Enter Site: ").lower() print("") #tells the user that the file contains the following. f = open('CONFIG-TO-SEND', 'r') file_contents = f.read() print_title("CONFIG-TO-SEND File contains the following information.\n") print(file_contents) print("") def baseconfig(push): # Send config textfile to targets push.run(task=netmiko_send_config, config_file= "config_textfile") push.run(task=netmiko_send_config, config_file="CONFIG-TO-SEND") targets = nr.filter(platform=inputplatform) targets1 = nr.filter(platform=inputplatform, role=inputrole) targets2 = nr.filter(platform=inputplatform, role=inputrole, site=inputsite) # Printing the entered information for extra clarification print_title( "You have now added filters, now it's time to apply them \n[P] Platform\n[PR] Platform,Role\n[PRS] Platform,Role,Site " ) applyfilter = input("Enter P,PR or PRS: ").lower() print() print_title("This is the information you have entered.\n") print("Platform: " + inputplatform) print("Role: " + inputrole)
import yaml from nornir import InitNornir from nornir_utils.plugins.functions import print_result, print_title from nornir_utils.plugins.tasks.data import load_yaml from nornir_jinja2.plugins.tasks import template_file from nornir_netmiko.tasks import netmiko_send_config from user_login import user_login from nornir.core.filter import F user_login() nr = InitNornir(config_file="config.yaml") task1 = nr.filter(F(groups__contains='spine')) vlan_list = [] name_list = [] multi_list = [] tenant_list = [] ip_list = [] vn_list = [] vn_seg_name = [] tenant = input('Enter tenant name : ') tenant_list.append(tenant) total = int(input('Enter total vlan : ')) for i in range(1, total): while len(vlan_list) < total: vlan = int(input('Please enter vlan %d no: ' % i)) name_vlan = str(input('Please enter vlan %d name: ' % i)) ip = str(input('Please enter %d ip address no: ' % i)) multi = str(input('Please enter %d multicast address no: ' % i)) vlan_list.append(vlan)
def getter_collector(): # noqa """ This function is the main function of the toolkit. It performs two roles: 1) Collects configurations for all devices in the inventory, based on NAPALM support. These configurations are saved in the configs/ directory using the following convention: <hostname>/<filter_name>.txt 2) Performs a collection of supported getters based on the official NAPALM supported filter list: https://napalm.readthedocs.io/en/latest/support/ It has been written in a way whereby one simply updates the appropriate <os>_getters list to add or remove supported getters. All getters are stored in the facts/ directory using the following convention: <hostname>/<filter_name>.json """ """ The following block of code is used to generate a log file in a directory. These log files will indicate the success/failure of filter collector for retrospective analysis. """ # Capture time cur_time = dt.datetime.now() # Cleanup time, so that the format is clean for the output file 2019-07-01-13-04-59 fmt_time = cur_time.strftime("%Y-%m-%d-%H-%M-%S") # Set log directory variable log_dir = "logs" # Create log directory if it doesn't exist. pathlib.Path(log_dir).mkdir(exist_ok=True) # Create log file name, with timestamp in the name filename = str("DISCOVERY-LOG") + "-" + fmt_time + ".txt" # Join the log file name and log directory together into a variable log_file_path = log_dir + "/" + filename # Create the log file log_file = open(log_file_path, "w") # Start of logging output print(f"{Fore.MAGENTA}STARTING DISCOVERY: " + str(fmt_time)) log_file.write("STARTING DISCOVERY: " + str(fmt_time) + "\n\n") """ Initialise two counters, so that success and failure can be counted and incremented as the getters are collected. """ # Success Counter success_count = 0 # Fail Counter fail_count = 0 # Initialize Nornir and define the inventory variables. nr = InitNornir( inventory={ "options": { "host_file": "inventory/hosts.yaml", "group_file": "inventory/groups.yaml", "defaults_file": "inventory/defaults.yaml", } }) # Set default username and password from environmental variables. nr.inventory.defaults.username = env_uname nr.inventory.defaults.password = env_pword """ The following block of lists are the supported getters per OS based on the website https://napalm.readthedocs.io/en/latest/support/ """ # IOS supported getters ios_getters = [ "arp_table", "bgp_neighbors", "bgp_neighbors_detail", "environment", "facts", "interfaces", "interfaces_counters", "interfaces_ip", "ipv6_neighbors_table", "lldp_neighbors", "lldp_neighbors_detail", "mac_address_table", "network_instances", "ntp_peers", "ntp_servers", "ntp_stats", "optics", "snmp_information", "users", ] # JUNOS supported getters junos_getters = [ "arp_table", "bgp_config", "bgp_neighbors", "bgp_neighbors_detail", "environment", "facts", "interfaces", "interfaces_counters", "interfaces_ip", "ipv6_neighbors_table", "lldp_neighbors", "lldp_neighbors_detail", "mac_address_table", "network_instances", "ntp_peers", "ntp_servers", "ntp_stats", "optics", "snmp_information", "users", ] # EOS supported getters eos_getters = [ "arp_table", "bgp_config", "bgp_neighbors", "bgp_neighbors_detail", "environment", "facts", "interfaces", "interfaces_counters", "interfaces_ip", "lldp_neighbors", "lldp_neighbors_detail", "mac_address_table", "network_instances", "ntp_servers", "ntp_stats", "optics", "snmp_information", "users", ] # NXOS supported getters nxos_getters = [ "arp_table", "bgp_neighbors", "facts", "interfaces", "interfaces_ip", "lldp_neighbors", "lldp_neighbors_detail", "mac_address_table", "ntp_peers", "ntp_servers", "ntp_stats", "snmp_information", "users", ] # IOSXR supported getters iosxr_getters = [ "arp_table", "bgp_config", "bgp_neighbors", "bgp_neighbors_detail", "environment", "facts", "interfaces", "interfaces_counters", "interfaces_ip", "lldp_neighbors", "lldp_neighbors_detail", "mac_address_table", "ntp_peers", "ntp_servers", "ntp_stats", "snmp_information", "users", ] """ The following block of code assigns a filter based on platform to a variable. This variable is used later on to apply logic in for loops """ ios_devices = nr.filter(platform="ios") junos_devices = nr.filter(platform="junos") eos_devices = nr.filter(platform="eos") nxos_devices = nr.filter(platform="nxos") iosxr_devices = nr.filter(platform="iosxr") """ The following block of code is a list of config getters which will be iterated over to collect the different config types per OS """ ios_config_getters = ["running", "startup"] junos_config_getters = ["running", "candidate"] eos_config_getters = ["running", "startup"] nxos_config_getters = ["running", "startup"] iosxr_config_getters = ["running", "startup"] """ The following block is the main component of the program. Each OS collects the running config, all supported getters and the startup/candidate config based on the OS. Each OS block is as uniform as possible. """ # IOS Platform Block for host in ios_devices.inventory.hosts.items(): # Assign the hostname to a variable from the host tuple hostname = host[0] # Starting processing of a host print(f"{Fore.MAGENTA}** Start Processing Host: " + str(hostname)) log_file.write("** Start Processing Host: " + str(hostname) + "\n") for config in ios_config_getters: # Start collecting the config getters print("Processing " + str(config) + " config ... ") log_file.write("Processing " + str(config) + " config ... " + "\n") # Execute the collect_config function configs = nr.run(task=collect_config, getter=config, on_failed=True) """ Access the specific 'napalm_get' result out of the collect_getters function and store whether the failed boolean is True (failure) or False (success) """ configs_results = configs[hostname][0].failed # Conditional block to record success/fail count of the 'napalm_get' result if configs_results is True: print(f"{Fore.RED}FAILURE : " + str(hostname) + " - " + str(config) + " config") log_file.write("FAILURE : " + str(hostname) + " - " + str(config) + " config" + "\n") fail_count += 1 else: print(f"{Fore.GREEN}SUCCESS : " + str(hostname) + " - " + str(config) + " config") log_file.write("SUCCESS : " + str(hostname) + " - " + str(config) + " config" + "\n") success_count += 1 # For block to collect all supported getters for entry in ios_getters: # Start processing getters print("Processing Getter: " + str(entry)) log_file.write("Processing Getter: " + str(entry) + "\n") # Execute collect_getters function getters = nr.run(task=collect_getters, getter=entry, on_failed=True) """ Access the specific 'napalm_get' result out of the collect_getters function and store whether the failed boolean is True (failure) or False (success) """ getters_results = getters[hostname][0].failed # Conditional block to record success/fail count of the 'napalm_get' result if getters_results is True: log_file.write("FAILURE : " + str(hostname) + " - " + str(entry) + "\n") print(f"{Fore.RED}FAILURE : " + str(hostname) + " - " + str(entry)) fail_count += 1 else: log_file.write("SUCCESS : " + str(hostname) + " - " + str(entry) + "\n") print(f"{Fore.GREEN}SUCCESS : " + str(hostname) + " - " + str(entry)) success_count += 1 # Ending processing of host print(f"{Fore.MAGENTA}** End Processing Host: " + str(hostname)) log_file.write("** End Processing Host: " + str(hostname) + "\n\n") # EOS Platform Block for host in eos_devices.inventory.hosts.items(): # Assign the hostname to a variable from the host tuple hostname = host[0] # Starting processing of a host print(f"{Fore.MAGENTA}** Start Processing Host: " + str(hostname)) log_file.write("** Start Processing Host: " + str(hostname) + "\n") for config in eos_config_getters: # Start collecting the config getters print("Processing " + str(config) + " config ... ") log_file.write("Processing " + str(config) + " config ... " + "\n") # Execute the collect_config function configs = nr.run(task=collect_config, getter=config, on_failed=True) """ Access the specific 'napalm_get' result out of the collect_getters function and store whether the failed boolean is True (failure) or False (success) """ configs_results = configs[hostname][0].failed # Conditional block to record success/fail count of the 'napalm_get' result if configs_results is True: print(f"{Fore.RED}FAILURE : " + str(hostname) + " - " + str(config) + " config") log_file.write("FAILURE : " + str(hostname) + " - " + str(config) + " config" + "\n") fail_count += 1 else: print(f"{Fore.GREEN}SUCCESS : " + str(hostname) + " - " + str(config) + " config") log_file.write("SUCCESS : " + str(hostname) + " - " + str(config) + " config" + "\n") success_count += 1 # For block to collect all supported getters for entry in eos_getters: # Start processing getters print("Processing Getter: " + str(entry)) log_file.write("Processing Getter: " + str(entry) + "\n") # Execute collect_getters function getters = nr.run(task=collect_getters, getter=entry, on_failed=True) """ Access the specific 'napalm_get' result out of the collect_getters function and store whether the failed boolean is True (failure) or False (success) """ getters_results = getters[hostname][0].failed # Conditional block to record success/fail count of the 'napalm_get' result if getters_results is True: log_file.write("FAILURE : " + str(hostname) + " - " + str(entry) + "\n") print(f"{Fore.RED}FAILURE : " + str(hostname) + " - " + str(entry)) fail_count += 1 else: log_file.write("SUCCESS : " + str(hostname) + " - " + str(entry) + "\n") print(f"{Fore.GREEN}SUCCESS : " + str(hostname) + " - " + str(entry)) success_count += 1 # Ending processing of host print(f"{Fore.MAGENTA}** End Processing Host: " + str(hostname)) log_file.write("** End Processing Host: " + str(hostname) + "\n\n") # NX-OS Platform Block for host in nxos_devices.inventory.hosts.items(): # Assign the hostname to a variable from the host tuple hostname = host[0] # Starting processing of a host print(f"{Fore.MAGENTA}** Start Processing Host: " + str(hostname)) log_file.write("** Start Processing Host: " + str(hostname) + "\n") for config in nxos_config_getters: # Start collecting the config getters print("Processing " + str(config) + " config ... ") log_file.write("Processing " + str(config) + " config ... " + "\n") # Execute the collect_config function configs = nr.run(task=collect_config, getter=config, on_failed=True) """ Access the specific 'napalm_get' result out of the collect_getters function and store whether the failed boolean is True (failure) or False (success) """ configs_results = configs[hostname][0].failed # Conditional block to record success/fail count of the 'napalm_get' result if configs_results is True: print(f"{Fore.RED}FAILURE : " + str(hostname) + " - " + str(config) + " config") log_file.write("FAILURE : " + str(hostname) + " - " + str(config) + " config" + "\n") fail_count += 1 else: print(f"{Fore.GREEN}SUCCESS : " + str(hostname) + " - " + str(config) + " config") log_file.write("SUCCESS : " + str(hostname) + " - " + str(config) + " config" + "\n") success_count += 1 # For block to collect all supported getters for entry in nxos_getters: # Start processing getters print("Processing Getter: " + str(entry)) log_file.write("Processing Getter: " + str(entry) + "\n") # Execute collect_getters function getters = nr.run(task=collect_getters, getter=entry, on_failed=True) """ Access the specific 'napalm_get' result out of the collect_getters function and store whether the failed boolean is True (failure) or False (success) """ getters_results = getters[hostname][0].failed # Conditional block to record success/fail count of the 'napalm_get' result if getters_results is True: log_file.write("FAILURE : " + str(hostname) + " - " + str(entry) + "\n") print(f"{Fore.RED}FAILURE : " + str(hostname) + " - " + str(entry)) fail_count += 1 else: log_file.write("SUCCESS : " + str(hostname) + " - " + str(entry) + "\n") print(f"{Fore.GREEN}SUCCESS : " + str(hostname) + " - " + str(entry)) success_count += 1 # Ending processing of host print(f"{Fore.MAGENTA}** End Processing Host: " + str(hostname) + "\n") log_file.write("** End Processing Host: " + str(hostname) + "\n\n") # JUNOS Platform Block for host in junos_devices.inventory.hosts.items(): # Assign the hostname to a variable from the host tuple hostname = host[0] # Starting processing of a host print(f"{Fore.MAGENTA}** Start Processing Host: " + str(hostname)) log_file.write("** Start Processing Host: " + str(hostname) + "\n") for config in junos_config_getters: # Start collecting the config getters print("Processing " + str(config) + " config ... ") log_file.write("Processing " + str(config) + " config ... " + "\n") # Execute the collect_config function configs = nr.run(task=collect_config, getter=config, on_failed=True) """ Access the specific 'napalm_get' result out of the collect_getters function and store whether the failed boolean is True (failure) or False (success) """ configs_results = configs[hostname][0].failed # Conditional block to record success/fail count of the 'napalm_get' result if configs_results is True: print(f"{Fore.RED}FAILURE : " + str(hostname) + " - " + str(config) + " config") log_file.write("FAILURE : " + str(hostname) + " - " + str(config) + " config" + "\n") fail_count += 1 else: print(f"{Fore.GREEN}SUCCESS : " + str(hostname) + " - " + str(config) + " config") log_file.write("SUCCESS : " + str(hostname) + " - " + str(config) + " config" + "\n") success_count += 1 for entry in junos_getters: # Start processing getters print("Processing Getter: " + str(entry)) log_file.write("Processing Getter: " + str(entry) + "\n") # Execute collect_getters function getters = nr.run(task=collect_getters, getter=entry, on_failed=True) """ Access the specific 'napalm_get' result out of the collect_getters function and store whether the failed boolean is True (failure) or False (success) """ getters_results = getters[hostname][0].failed # Conditional block to record success/fail count of the 'napalm_get' result if getters_results is True: log_file.write("FAILURE : " + str(hostname) + " - " + str(entry) + "\n") print(f"{Fore.RED}FAILURE : " + str(hostname) + " - " + str(entry)) fail_count += 1 else: log_file.write("SUCCESS : " + str(hostname) + " - " + str(entry) + "\n") print(f"{Fore.GREEN}SUCCESS : " + str(hostname) + " - " + str(entry)) success_count += 1 # Ending processing of host print("** End Processing Host: " + str(hostname) + "\n") log_file.write("** End Processing Host: " + str(hostname) + "\n\n") # IOS-XR Platform Block for host in iosxr_devices.inventory.hosts.items(): # Assign the hostname to a variable from the host tuple hostname = host[0] # Starting processing of a host print(f"{Fore.MAGENTA}** Start Processing Host: " + str(hostname)) log_file.write("** Start Processing Host: " + str(hostname) + "\n") for config in iosxr_config_getters: # Start collecting the config getters print("Processing " + str(config) + " config ... ") log_file.write("Processing " + str(config) + " config ... " + "\n") # Execute the collect_config function configs = nr.run(task=collect_config, getter=config, on_failed=True) """ Access the specific 'napalm_get' result out of the collect_getters function and store whether the failed boolean is True (failure) or False (success) """ configs_results = configs[hostname][0].failed # Conditional block to record success/fail count of the 'napalm_get' result if configs_results is True: print(f"{Fore.RED}FAILURE : " + str(hostname) + " - " + str(config) + " config") log_file.write("FAILURE : " + str(hostname) + " - " + str(config) + " config" + "\n") fail_count += 1 else: print(f"{Fore.GREEN}SUCCESS : " + str(hostname) + " - " + str(config) + " config") log_file.write("SUCCESS : " + str(hostname) + " - " + str(config) + " config" + "\n") success_count += 1 # For block to collect all supported getters for entry in iosxr_getters: # Start processing getters print("Processing Getter: " + str(entry)) log_file.write("Processing Getter: " + str(entry) + "\n") # Execute collect_getters function getters = nr.run(task=collect_getters, getter=entry, on_failed=True) """ Access the specific 'napalm_get' result out of the collect_getters function and store whether the failed boolean is True (failure) or False (success) """ getters_results = getters[hostname][0].failed # Conditional block to record success/fail count of the 'napalm_get' result if getters_results is True: log_file.write("FAILURE : " + str(hostname) + " - " + str(entry) + "\n") print(f"{Fore.RED}FAILURE : " + str(hostname) + " - " + str(entry)) fail_count += 1 else: log_file.write("SUCCESS : " + str(hostname) + " - " + str(entry) + "\n") print(f"{Fore.GREEN}SUCCESS : " + str(hostname) + " - " + str(entry)) success_count += 1 # Ending processing of host print("** End Processing Host: " + str(hostname)) log_file.write("** End Processing Host: " + str(hostname) + "\n\n") # Add the two variables together to get a total count into a variable total_count = success_count + fail_count # Provide a summary of the main function and add to log file print("SUMMARY" + "\n") log_file.write("SUMMARY" + "\n\n") print(f"{Fore.GREEN}SUCCESS COUNT : " + str(success_count)) log_file.write("SUCCESS COUNT : " + str(success_count) + "\n") print(f"{Fore.RED}FAILURE COUNT : " + str(fail_count)) log_file.write("FAILURE COUNT : " + str(fail_count) + "\n") print("TOTAL COUNT : " + str(total_count)) log_file.write("TOTAL COUNT : " + str(total_count) + "\n") # Close the log file log_file.close()
# create a console handler with a higher log level console_handler = logging.StreamHandler() console_handler.setLevel(logging.INFO) # Adds the handlers to the logger logger.addHandler(file_handler) logger.addHandler(console_handler) if __name__ == "__main__": nr = InitNornir(config_file='config.yaml') #nr = InitNornir(config_file='config.yaml', core={'num_workers': 1}) #common filters routers = nr.filter(F(groups__contains='Routers')) switches = nr.filter(F(groups__contains='Switches')) r1_r2 = nr.filter(F(hostname='r1') | F(hostname='r2')) r2_simple = nr.filter(hostname='r2') #Unfiltered task rend_conf = nr.run(task=render_configs) #Filtered task #filter_inv = routers #rend_conf = filter_inv.run(task=render_configs) print_result(rend_conf) sys.exit()
netconf_lock, netconf_unlock, netconf_edit_config, netconf_get, netconf_get_config, netconf_rpc, netconf_commit, ) __author__ = "Hugo Tinoco" __email__ = "*****@*****.**" nr = InitNornir("config.yml") # Filter the hosts by the 'west-region' site key. west_region = nr.filter(region="west-region") def createFolder(directory): try: if not os.path.exists(directory): os.makedirs(directory) except OSError: print("Error: Creating directory. " + directory) def data_validation(task): """Load the input YAML data and validate required values are present.""" # Load Data loaded_data = task.run(task=load_yaml, file=f"data/{task.host}.yml")
from nornir import InitNornir import ipdb def netmiko_direct(task): # Manually create Netmiko connection ipdb.set_trace() net_connect = task.host.get_connection("netmiko", task.nornir.config) print(net_connect.find_prompt()) output = net_connect.send_command("show ip int brief") print(output) if __name__ == "__main__": nr = InitNornir(config_file="config.yaml") nr = nr.filter(name="cisco1") nr.run(task=netmiko_direct)
nr = InitNornir( runner={ "plugin": "threaded", "options": { "num_workers": 100, }, }, inventory={ 'plugin': 'LabInventory', 'options': { 'hostsfile': 'hosts.yaml', }, }, ) cisco_hosts = nr.filter(name='R11') nr.inventory.defaults.username = "******" nr.inventory.defaults.password = "" # print(cisco_hosts.inventory.hosts) # results = cisco_hosts.run(napalm_get, getters=['get_interfaces_ip'], severity_level=logging.DEBUG, ssh_private_key_file="~/.ssh/id_rsa") send_command_results = cisco_hosts.run(task=send_command, command="show ip interface brief") print_result(send_command_results) print(nr.config.inventory.plugin) print(nr.inventory.hosts) print(nr.inventory.groups) ipdb.set_trace() # pprint.pprint(len(nr.inventory.hosts)) # print(json.dumps(nr.inventory.hosts, indent=4))
def main(): nr = InitNornir(config_file="config.yaml") nr = nr.filter(F(groups__contains="eos") | F(groups__contains="nxos")) result = nr.run(task=configure_vlan, vlan_id="123", vlan_name="ntp_vlan") print_result(result)
def main(): nr = InitNornir(config_file="config.yaml") nr = nr.filter(name="srx2") nr.run(task=junos_acl)
# source: https://nornir.readthedocs.io/en/latest/howto/advanced_filtering.html from nornir import InitNornir from nornir.core.filter import F nr = InitNornir(config_file="./inventory/advanced_filtering/config.yaml") print(nr.inventory.hosts) print(nr.inventory.groups) # All the following filters the dict-like inventory # DUNDER/MAGIC METHOD has __ at the beginning and is notionally hidden # and not generally called as an object method. # __contains birds = nr.filter(F(groups__contains="bird")) print(birds.inventory.hosts.keys()) print(birds.inventory.hosts.values()) # invert by prepending ~ not_birds = nr.filter(~F(groups__contains="bird")) print(not_birds.inventory.hosts.keys()) # OR domestic_or_bird = nr.filter(F(groups__contains="bird") | F(domestic=True)) print(domestic_or_bird.inventory.hosts.keys()) # AND domestic_mammals = nr.filter(F(groups__contains="mammal") & F(domestic=True)) print(domestic_mammals.inventory.hosts.keys()) # combination
import nornir.core from nornir import InitNornir from nornir.plugins.tasks import commands from nornir.plugins.functions.text import print_result from nornir.plugins.tasks import networking nr = InitNornir(config_file="config.yaml") facts_test = nr.filter(site="nyc", role="leaf") result = facts_test.run(task=networking.napalm_cli, commands=["show version"]) print_result(result)
def backup_configurations(task): commands = "show run", "show cdp neighbor detail", "show version" for cmd in commands: config_dir = "config-archive" date_dir = config_dir + "/" + str(date.today()) hotel_dir = date_dir + "/" + str(hotel_code) command_dir = hotel_dir + "/" + cmd pathlib.Path(config_dir).mkdir(exist_ok=True) pathlib.Path(date_dir).mkdir(exist_ok=True) pathlib.Path(hotel_dir).mkdir(exist_ok=True) pathlib.Path(command_dir).mkdir(exist_ok=True) r = task.run(task=netmiko_send_command, command_string=cmd) task.run( task=write_file, content=r.result, filename=f"" + str(command_dir) + "/" + task.host.name + ".txt", ) #result = nr.run( #name="Creating Backup Archive", task=backup_configurations #) targets = nr.filter(hotel_code="sab") result = targets.run(name="Creating Backup Archive", task=backup_configurations) print_result(result)
from nornir.plugins.tasks import networking from nornir.plugins.functions.text import print_result from nornir.plugins.tasks.files import write_file from nornir import InitNornir from nornir.core.filter import F BACKUP_PATH = "./configs" def backup_config(task, path): r = task.run(task=networking.napalm_get, getters=["config"]) task.run( task=write_file, content=r.result["config"]["running"], filename=f"{path}/{task.host}.txt", ) nr = InitNornir(config_file="./config.yml") devices = nr.filter((F(groups__contains="CSR_Routers"))) result = devices.run( name="Backup Device Configurations", path=BACKUP_PATH, task=backup_config ) print_result(result, vars=["stdout"])
from nornir_pyez.plugins.tasks import pyez_config, pyez_diff, pyez_commit from nornir import InitNornir from nornir_utils.plugins.functions import print_result from nornir.core.filter import F import os script_dir = os.path.dirname(os.path.realpath(__file__)) nr = InitNornir(config_file=f"{script_dir}/config.yml") junos_devices = nr.filter(F(node_type="switch")) def lacp_config(task): data = {} data['lacp'] = task.host['lacp'] if data['lacp']: data['lacp_int_name'] = {} for inte in task.host['lacp_int_name']: data['lacp_int_name'][inte] = True print(data) chassis_response = task.run( name='lacp chassis config', task=pyez_config, template_path= '/mnt/c/Code/CodeSamples/Python/Networking/Nornir/lacp_chassis.j2', template_vars=data, data_format='xml') if chassis_response: diff = task.run(task=pyez_diff, name='int diff') if diff:
def main(): nr = InitNornir(config_file="config.yaml", logging={"enabled": False}) nxos1 = nr.filter(name="nxos1") scp_job = nxos1.run(task=scp_copy, num_workers=1) delete_job = nxos1.run(task=netmiko_prompting_del, num_workers=1)
def main(): nr = InitNornir(config_file="config.yaml") nr = nr.filter(name="arista1") agg_result = nr.run(task=render_configurations) print(agg_result["arista1"].result) print("Complete!")
def run_nssa_config(ospf_area): nr = InitNornir(config_file=f"{config_file}") nr = nr.filter(F(ospf_area__contains=int(ospf_area))) result = nr.run(task=not_so_stubby_area_config, area=ospf_area) print_result(result)
def kickoff(): """ Nornir kickoff function to initialize inventory and set or confirm credentials """ # check arguments for site code if len(sys.argv) < 2: # set no site code site = "" site_ = "" else: # set site code site = sys.argv[1] site_ = sys.argv[1] + "_" # print banner print() print("~" * 80) # initialize The Norn nr = InitNornir( logging={ "file": f"logs/{site_}nornir_log.txt", "level": "debug" }, inventory={ "plugin": "nornir.plugins.inventory.simple.SimpleInventory", "options": { "host_file": f"inventory/{site_}hosts.yaml", "group_file": f"inventory/{site_}groups.yaml", "defaults_file": "inventory/defaults.yaml", }, }, ) # filter The Norn nr = nr.filter(platform="ios") if len(nr.inventory.hosts) == 0: c_print("*** No matching hosts found in inventory ***") print("~" * 80) exit() else: c_print( "This script will apply IBNS dot1x configurations to Cisco Catalyst switches" ) c_print(f"Inventory includes the following devices {site}:") for host in nr.inventory.hosts.keys(): c_print(f"*** {host} ***") c_print("Checking inventory for credentials") # check for existing credentials in inventory if nr.inventory.defaults.username == None or nr.inventory.defaults.password == None: c_print("Please enter device credentials:") if nr.inventory.defaults.username == None: nr.inventory.defaults.username = input("Username: "******"~" * 80) return nr
def manage_users(task, desired_users): state_users = task.run(task=napalm_get, getters=["users"], severity_level=logging.DEBUG) users_to_remove = [] for user in state_users.result["users"]: if user not in desired_users: users_to_remove.append(user) users_config = task.run( task=template_file, path=f"templates/{task.host.platform}", template="users.j2", desired_users=desired_users, remove_users=users_to_remove, severity_level=logging.DEBUG, ) task.run(task=napalm_configure, configuration=users_config.result) yaml = ruamel.yaml.YAML() with open("data/users.yaml", "r") as f: desired_users = yaml.load(f.read()) spines = nr.filter(role="spine") r = spines.run(task=manage_users, desired_users=desired_users) print_result(r)
def main(): nr = InitNornir(config_file="config.yaml") nr = nr.filter(name="srx2") agg_result = nr.run(task=send_command) print_result(agg_result)
except: vrf = '' try: p2p = Dict_config_p2p[Node] except: p2p = '' try: routing = Dict_config_routing[Node] except: routing = '' Dict_config_final[Node] = (vrf + '\n' + p2p + '\n' + routing).strip('\n') for hostname, config in Dict_config_final.items(): with open(os.path.join(candidate_path, '{}.txt'.format(hostname)), mode='w') as f: f.write(config) #hosts = ['host1'] nr = InitNornir(config_file="config.yaml") for H in NodeSetFinal: node = nr.filter(node=H) print('configuration of {} is under process'.format(H)) config_set = Dict_config_final[H] config_set = config_set.strip('\n') result = node.run(task=netmiko_send_config, config_commands=config_set) print_result(result)
from nornir import InitNornir from nornir.plugins.tasks.text import template_string if __name__ == "__main__": TEMPLATE_STR = """ interface loopback{{ int_num }} description {{ descr | lower }} no shut """ nr = InitNornir(config_file="config.yaml", logging={"enabled": False}) nr = nr.filter(name="srx2") my_vars = { "int_num": "99", "descr": "My Description", } agg_result = nr.run(task=template_string, template=TEMPLATE_STR, **my_vars) print() print("-" * 40) print(agg_result["srx2"][0].result) print("-" * 40) print()
def main(): nr = InitNornir(config_file="config.yaml") nr = nr.filter(F(groups__contains="eos") | F(groups__contains="ios")) agg_result = nr.run(task=set_snmp_id) print_result(agg_result)
def main(): nr = InitNornir(config_file="config.yaml") nr = nr.filter(F(groups__contains="eos")) result = nr.run(task=file_copy) print_result(result)
#!/usr/bin/env python from pprint import pprint as pp from nornir import InitNornir from nornir.plugins.tasks.networking import netmiko_send_command nr = InitNornir(config_file="config.yaml") nr = nr.filter(platform="ios") my_results = nr.run(task=netmiko_send_command, command_string="show run | inc hostname") host_results = my_results['cisco3'] task_result = host_results[0] #print(my_results) #print(my_results.items()) #print(host_results) #for k in host_results: #print(k) print(task_result) #print(dir(task_result)) #print(task_result.host) #print(task_result.name) print(task_result.result) #print(task_result.failed) print(type(my_results))
def main(): nr = InitNornir(config_file="config.yaml") nr = nr.filter(F(groups__contains="eos")) nr_with_processors = nr.with_processors([PrintResult()]) nr_with_processors.run(task=get_version)
from nornir import InitNornir from nornir_utils.plugins.functions import print_result import datetime, os, xmltodict, json, sys from nornir_utils.plugins.tasks.files import write_file from nornir_netconf.plugins.tasks import netconf_get_config __author__ = "Hugo Tinoco" __email__ = "*****@*****.**" # Specify a custom config yaml file. nr = InitNornir("config.yml") # Filter the hosts by the 'west-region' site key. netconf_devices = nr.filter(operation="netconf-enabled") def create_folder(directory): """Helper function to automatically generate directories""" try: if not os.path.exists(directory): os.makedirs(directory) except OSError: print("Error: Creating directory. " + directory) def xml2json(xmlconfig): """Simple function to conver the extract xml config and convert it to JSON str""" try: xml = xmltodict.parse(str(xmlconfig)) return json.dumps(xml, indent=2) except Exception as e: