from nornir import InitNornir from nornir.core.filter import F from nornir.plugins.tasks.networking import netmiko_send_command from nornir.plugins.functions.text import print_result from pprint import pprint as pp def my_task(task): #print(dir(task)) task.run(name="ip", task=netmiko_send_command, command_string="show ip int brief", use_textfsm=True) nr=InitNornir(config_file="../../config.yaml") print(f"{nr.config.core.num_workers}") ios_filt = F(groups__contains="ios") nr = nr.filter(ios_filt) print(nr.inventory.hosts) nr.inventory.hosts["cisco3"].password = '******' agg_results=nr.run(task=my_task) print_result(agg_results) print(agg_results.failed_hosts) print(nr.data.failed_hosts)
def main() -> None: nr = InitNornir(config_file="config.yaml") result = nr.run(task=underlay) print_result(result)
def main(): nr = InitNornir(config_file="config.yaml") filt = F(groups__contains="nxos") nxos = nr.filter(filt) agg_result = nxos.run(task=direct, num_workers=1) print_result(agg_result)
def _install_frr_cumulus(self, task): install_cmds = "sudo apt install -y frr" res = task.run(task=self.run_remote_cmd, cmd=install_cmds) print_result(res)
strip_prompt=False, strip_command=False) # Verify the file is actually gone. cmd = f"dir {filename}" new_output = net_connect.send_command_timing(cmd, strip_prompt=False, strip_command=False) if "No such file or directory" not in new_output: raise ValueError("The file was not properly deleted") return output if __name__ == "__main__": nr = InitNornir(config_file="config.yaml") nr = nr.filter(name="nxos1") # Transfer test file to NX-OS devices source_file = "bonus1_ex4.txt" dest_file = source_file agg_result = nr.run( netmiko_file_transfer, source_file=source_file, dest_file=dest_file, direction="put", ) print_result(agg_result) agg_result = nr.run(task=delete_file, filename=source_file) print_result(agg_result)
return config def main(): print_title("Deploy INFRA DIRECTORY") deploy_directory() print_title("Get Host Fact Using NAPALM") result = nr.filter(site="CUCA", role="core-switch").run(task=get_host_fact) print_result(result) print_title("Perform a Backup before Changes") nr.filter(site="CUCA", role="core-switch").run(task=get_backup) print_title("Send Template to HOST") output = nr.filter(site="CUCA", role="core-switch").run(task=interface_templates) print_result(output) if __name__ == '__main__': print_title("PUSH TEMPLATE to HOST") output = nr.filter(site="CUCA", role="core-switch").run(task=push_templates) #output = nr.filter(site="CUCA", role="core-switch").run(task=bgp_templates) print_result(output) #print(nr.inventory.hosts['CoreSPINEcuca01']['asn']) #print(nr.inventory.hosts['CoreSPINEcuca01']['vlans']) #print(get_bgp_peer())
def main() -> None: nr = InitNornir(config_file="config.yaml") result = nr.run(task=get_facts) print_result(result)
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)
if __name__ == "__main__": import ipdb ipdb.set_trace() nr = InitNornir(config_file="config2.yaml") aggr_result = nr.run(task=netmiko_send_command, command_string="show configuration") print(aggr_result.failed) print(aggr_result.failed_hosts.keys()) # Run second task on only successful hosts aggr_result = nr.run(task=netmiko_send_command, command_string="show arp") print_result(aggr_result) # Run a task on the failed hosts aggr_result = nr.run(task=failed_task, on_failed=True, on_good=False) # Recover specific host print(f"Failed Hosts: {nr.data.failed_hosts}") nr.data.recover_host("vmx2") # Reset failed hosts print(f"Failed Hosts: {nr.data.failed_hosts}") print("Reset failed hosts") nr.data.reset_failed_hosts() print(f"Failed Hosts: {nr.data.failed_hosts}")
def main(): nr = InitNornir(config_file="nornir.yaml") lab = nr.filter(F(groups__contains="ti_lfa")) aggresult = lab.run(task=show_frr) print_result(aggresult)
def calling_api(self, url, method): local = self._nornir.filter(F(platform="linux")) api_res = local.run(task=apis.http_method, method=method, url=url) print_result(api_res)
def run_remote_cmd(task, cmd): res = task.run(commands.remote_command, command=cmd) print_result(res)
def linux_local_cmd(self, cmd): local = self._nornir.filter(F(role="local")) cmd_res = local.run(task=commands.command, command=cmd) print_result(cmd_res)
def load_vlan(task): v = task.run(task=template_file, template="vlan.j2", path="./templates") task.host["vlan_config"] = v.result vlan_output = task.host["vlan_config"] vlan_send = vlan_output.splitlines() task.run(task=netmiko_send_config, name="VLAN Commands", config_commands=vlan_send) yaml_targets = nr.filter(all="yes") yaml_results = yaml_targets.run(task=load_vars) base_targets = nr.filter(all="yes") base_results = base_targets.run(task=load_base) isis_targets = nr.filter(routing="yes") isis_results = isis_targets.run(task=load_isis) ether_targets = nr.filter(etherchannel="yes") ether_results = ether_targets.run(task=load_ether) trunk_targets = nr.filter(trunking="yes") trunk_results = trunk_targets.run(task=load_trunking) vlan_targets = nr.filter(vlan="yes") vlan_results = vlan_targets.run(task=load_vlan) print_result(yaml_results) print_result(base_results) print_result(isis_results) print_result(ether_results) print_result(trunk_results) print_result(vlan_results) print_result(base_results)
def main(): nr = InitNornir(config_file="config.yaml") nr = nr.filter(F(groups__contains="eos")) result = nr.run(task=file_copy, num_workers=1) print_result(result)
config_commands=eigrp_commands) # General Configuration for All Routers def general_config(task): task.run(task=netmiko_send_config, config_file="general_config") task.run(task=netmiko_send_command, command_string="show run") # Internal IS-IS isis_internal_routers = nr.filter(type="internal_isis") results = isis_internal_routers.run(task=isis_internal) print_title("DEPLOYING CONFIGURATIONS") print_result(results) # Edge IS-IS isis_edge_routers = nr.filter(type="edge_isis") results = isis_edge_routers.run(task=isis_edge) print_title("DEPLOYING CONFIGURATIONS") print_result(results) # Internal OSPF ospf_internal_routers = nr.filter(type="internal_ospf") results = ospf_internal_routers.run(task=ospf_internal) print_title("DEPLOYING CONFIGURATIONS") print_result(results)
def main(): # Create instance using default hosts.yaml and groups.yaml nr = InitNornir(config_file='config.yaml') # print(dir(nr)) print("Hosts derived from the Inventory file are: \t{}".format( nr.inventory.hosts)) print("Groups derived from the Inventory file are: \t{}".format( nr.inventory.groups)) print("\nDecomposing Groups...") my_groups = nr.inventory.groups group_keys = list(my_groups.keys()) print("Group keys = {} of type {} ".format(group_keys, type(group_keys))) for i in group_keys: print(f"- {i}") print("\nDecomposing Hosts...") my_hosts = nr.inventory.hosts print("Type of nr.inventory.hosts in var my_hosts is {}".format( type(my_hosts))) host_keys = list(my_hosts.keys()) print("Host keys = {} of type {} ".format(host_keys, type(host_keys))) for i in host_keys: print(f"- {i}") print("\n") # Like Ansible, Nornir will execute the run instructions on all the devices defined in the environment print(f"Logging into hosts in inventory and getting napalm facts...") result = nr.run(napalm_get, getters=['get_facts']) print(f"napalm facts stored in the variable 'result'...") # Printing now may help you decompose the resulting objects print_result(result) print(f"\nDecomposing Nornir Result Object of type {type(result)}...\n") for i in result: print( f"Iterating through result object of type{type(result[i])} for item {i}" ) print(f"\tGet the top level key(s) for the device:") # Make sure there result is a dict if type(result[i].result) == dict: top_result_keys = result[i].result.keys() print(f"\t{top_result_keys}") # Example output: dict_keys(['get_facts']) print(f"\n\tGet the next level of key(s):") next_keys = result[i].result['get_facts'].keys() print(f"\t{next_keys}") # Example output: dict_keys(['uptime', 'vendor', 'os_version', 'serial_number', 'model', 'hostname', 'fqdn', 'interface_list']) # Iterate through the keys and values print(f"\tDecomposing Result Object for hostname {i}...") for k in next_keys: print( f"\t\tKey {k} \t has Value: {result[i].result['get_facts'][k]}" ) print("\n") else: print( f"\n\tERROR! DevNet Sandbox devices may be too busy. Try script again." ) print( f"\nPrint run results with the print_result module." "\nThis is a built-in Ansible like run status that will format the output for easy viewing..." ) print_result(result)
import ipaddress as ipad from nornir import InitNornir from nornir.plugins.tasks.text import template_file from nornir.plugins.tasks.networking import netmiko_send_config, netmiko_save_config, napalm_get from nornir.plugins.functions.text import print_result nr = InitNornir(config_file="config.yaml") def ospf_enabled(host): return 'ospf' in host.data['services'] def configure_ospf(task): task.host['template_config'] = task.run(task=template_file, template='ospf_template.j2', path='templates') task.run(task=netmiko_send_config, config_commands=task.host['template_config'].result) task.run(task=netmiko_save_config) task.run(task=napalm_get, getters=['facts', 'get_interfaces_ip']) routers = nr.filter(filter_func=ospf_enabled) r = routers.run(configure_ospf) print_result(r)
def main() -> None: with InitNornir(config_file="nr-config.yaml") as nr: results = nr.run(fetch_and_parse_lldp_neighbors) print_result(results)
def main(): nr = InitNornir(config_file="config.yaml") result = nr.run(name="Creating Backup Archive", task=backup_config) print_result(result)
def main() -> None: clean_up = "rm -r configs-diff current-config" os.system(clean_up) os.system(clear_command) nr = InitNornir(config_file="config.yaml") wipe_targets = nr.filter(all="yes") wipe_results = wipe_targets.run(task=rollback_golden) yaml_targets = nr.filter(all="yes") yaml_results = yaml_targets.run(task=load_vars) base_targets = nr.filter(all="yes") base_results = base_targets.run(task=load_base) isis_targets = nr.filter(routing="yes") isis_results = isis_targets.run(task=load_isis) ether_targets = nr.filter(etherchannel="yes") ether_results = ether_targets.run(task=load_ether) trunk_targets = nr.filter(trunking="yes") trunk_results = trunk_targets.run(task=load_trunking) vlan_targets = nr.filter(vlan="yes") vlan_results = vlan_targets.run(task=load_vlan) print_result(wipe_results) print_result(yaml_results) print_result(base_results) print_result(isis_results) print_result(ether_results) print_result(trunk_results) print_result(vlan_results)
from nornir import InitNornir from nornir.core.filter import F from nornir.plugins.tasks.networking import netmiko_send_command from nornir.plugins.functions.text import print_result nr = InitNornir(config_file="config.yml") asas = nr.filter((F(name__contains="ASAv-1"))) result = asas.run(netmiko_send_command, command_string="show version | inc So|Serial| up") print_result(result)
def print_result(self, result): print(self.expected) print_result(result)
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)
failed_tasks = {} for host, data in {k: v[1] for (k, v) in validate_result.items()}.items(): for test, output in data.result.items(): if test == "skipped": pass elif test == "complies": pass elif output["complies"] is False: failed_tasks.setdefault(host, []).append(test) return failed_tasks if __name__ == "__main__": backup_task = nr.run(task=backup_configs) if any(r[0].failed is True for r in backup_task.values()): print_result(backup_task) print("Couldn't backup configs, exiting before causing any chaos!...") sys.exit(1) else: print("Backups completed successfully!") write_task = nr.run(task=write_configs, backup=True) if any(r[0].failed is True for r in write_task.values()): print_result(write_task) else: print("Writing backups to disk completed successfully!") render_task = nr.run(task=render_configs) if any(r[0].failed is True for r in render_task.values()): print_result(render_task) else: