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!")
def reset_access_device(self): nr = cnaas_nms.confpush.nornir_helper.cnaas_init() nr_filtered = nr.filter(name=self.testdata['init_access_new_hostname']) nr_filtered.inventory.hosts[self.testdata['init_access_new_hostname']].\ connection_options["napalm"] = ConnectionOptions(extras={"timeout": 5}) data_dir = pkg_resources.resource_filename(__name__, 'data') with open(os.path.join(data_dir, 'access_reset.j2'), 'r') as f_reset_config: print(self.testdata['init_access_new_hostname']) config = f_reset_config.read() print(config) nrresult = nr_filtered.run( task=napalm_configure, name="Reset config", replace=False, configuration=config, dry_run=False # TODO: temp for testing ) print_result(nrresult) reset_interfacedb(self.testdata['init_access_new_hostname']) with sqla_session() as session: dev: Device = session.query(Device).filter( Device.hostname == self.testdata['init_access_new_hostname']).one() dev.management_ip = None dev.hostname = self.testdata['init_access_old_hostname'] dev.state = DeviceState.DISCOVERED dev.device_type = DeviceType.UNKNOWN
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()
def generate_only(hostname: str) -> (str, dict): """ Generate configuration for a device and return it as a text string. Args: hostname: Hostname of device generate config for Returns: (string with config, dict with available template variables) """ logger = get_logger() nr = cnaas_init() nr_filtered, _, _ = inventory_selector(nr, hostname=hostname) template_vars = {} if len(nr_filtered.inventory.hosts) != 1: raise ValueError("Invalid hostname: {}".format(hostname)) try: nrresult = nr_filtered.run(task=push_sync_device, generate_only=True) if nrresult[hostname][0].failed: raise Exception("Could not generate config for device {}: {}".format( hostname, nrresult[hostname][0].result )) if "template_vars" in nrresult[hostname][1].host: template_vars = nrresult[hostname][1].host["template_vars"] if nrresult.failed: print_result(nrresult) raise Exception("Failed to generate config for {}".format(hostname)) return nrresult[hostname][1].result, template_vars except Exception as e: logger.exception("Exception while generating config: {}".format(str(e))) if len(nrresult[hostname]) >= 2: return nrresult[hostname][1].result, template_vars else: return str(e), template_vars
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 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)
def main(): nr = InitNornir(config_file="config.yaml") for hostname, host_obj in nr.inventory.hosts.items(): if random.choice([True, False]): host_obj.password = BAD_PASSWORD agg_result = nr.run(task=send_command) print_result(agg_result)
def pre_init_checks(session, device_id) -> Device: """Find device with device_id and check that it's ready for init, returns Device object or raises exception""" # Check that we can find device and that it's in the correct state to start init dev: Device = session.query(Device).filter( Device.id == device_id).one_or_none() if not dev: raise ValueError(f"No device with id {device_id} found") if dev.state != DeviceState.DISCOVERED: raise DeviceStateException( "Device must be in state DISCOVERED to begin init") old_hostname = dev.hostname # Perform connectivity check nr = cnaas_nms.confpush.nornir_helper.cnaas_init() nr_old_filtered = nr.filter(name=old_hostname) try: nrresult_old = nr_old_filtered.run(task=napalm_get, getters=["facts"]) except Exception as e: raise ConnectionCheckError( f"Failed to connect to device_id {device_id}: {str(e)}") if nrresult_old.failed: print_result(nrresult_old) raise ConnectionCheckError( f"Failed to connect to device_id {device_id}") return dev
def main(): credentials = get_credentials.get_credentials() nr = InitNornir(config_file="nornir_data/config.yaml") nr.inventory.defaults.username = credentials["username"] nr.inventory.defaults.password = credentials["password"] #nr = nr.filter(F(groups__contains="test_subject")) lock = nr.run(task=config_lock) print_result(lock) results = nr.run(task=load_vars) print_result(results) failed_changes = nr.data.failed_hosts if failed_changes: revert = nr.run(task=config_discard) print_result(revert) for device in failed_changes: fail_report( device, results[device].exception, ) else: commit_config = nr.run(task=config_commit) print_result(commit_config) unlock = nr.run(task=config_unlock) print_result(unlock)
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 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 agg_result = nr.run(task=napalm_get, getters=["config"]) print_result(agg_result)
def main(): # Decrypt the credentials for all devices from the encrypted file via Ansible vault credentials = get_credentials.get_credentials() # Instantiate Nornir with given config file nr = InitNornir(config_file="nornir_data/config.yaml") # Assign the decrypted credentials to default username/password values for the devices in Nornir inventory nr.inventory.defaults.username = credentials["username"] nr.inventory.defaults.password = credentials["password"] # Lock the configuration of all devices to prevent other users from issuing any changes lock = nr.run(task=config_lock) print_result(lock) # Load host variables, build templates for all specified features and push to the candidate configuration results = nr.run(task=load_vars) print_result(results) # Verify if any config build or config push has failed # If everything was successful, commit the configuration from candidate to running # Otherwise, discard the candidate configuration and issue a fail report failed_changes = nr.data.failed_hosts if failed_changes: revert = nr.run(task=config_discard) print_result(revert) for device in failed_changes: fail_report(device, results[device].exception,) else: commit_config = nr.run(task=config_commit) print_result(commit_config) # Unlock the devices configuration unlock = nr.run(task=config_unlock) print_result(unlock)
def main(filt, task): global nfilt_filter nfilt_filter = build_F(filt) todo = build_tasks(task) #print(todo) #override cli argument in code? # #override filers #filt = ['groups__contains:wilma','tag:fred'] #nfilt_filter = build_F(filt) # #override tasks #task = ['show:run','sayhello'] #todo = build_tasks(task) nr = InitNornir(config_file='dec-config.yaml') #or skip the decorator altogether and just use nr.filter with cli arguments #nr = nr.filter(nfilt_filter) result = nr.run(task=do_task, todo=todo, name="Tasks") print_result(result)
def main(): credentials = get_credentials.get_credentials() nr = InitNornir(config_file="nornir_data/config.yaml") nr.inventory.defaults.username = credentials["username"] nr.inventory.defaults.password = credentials["password"] vpn_test_results = nr.run(task=vpn_test, ) print_result(vpn_test_results)
def main() -> None: clean_up = "rm -r ospfdiff ospf-current" os.system(clean_up) os.system(clear_command) nr = InitNornir(config_file="config.yaml") output = nr.run(task=clean_ospf) print_title("REVERSING OSPF CONFIGURATION BACK INTO DESIRED STATE") print_result(output)
def run_ospf_config(device, group): 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=ospf_config) print_result(result)
def main(): """ Here's the good stuff """ dotenv_file = find_dotenv() load_dotenv(dotenv_path=dotenv_file, verbose=True) ## NetBox Stuff nb_host=getenv('nb_host') nb_url=f"http://{nb_host}" nb_token=getenv('nb_token') ## Napalm Stuff username=getenv('username') password=getenv('password') secret=getenv('secret') netbox:NetBox = NetBox(host=nb_host, auth_token=nb_token, ssl_verify=False, use_ssl=False, port=80) nb_interfaces:list = netbox.dcim.get_interfaces() nornir_instance = InitNornir( inventory={ "plugin":"NetBoxInventory2", "options": { "nb_url": nb_url, "nb_token": nb_token } }, logging={ "enabled": True, "level": "INFO", # DEBUG is most verbose "to_console": False, # True returns ALOT of stuff } ) for host in nornir_instance.inventory.hosts.keys(): nornir_instance.inventory.hosts[host].connection_options = create_connection_options( username=username, password=password, secret=secret) ## Advanced Filtering using F object and `magic` double underscore notation. ## https://nornir.readthedocs.io/en/latest/howto/advanced_filtering.html filtered_inventory = nornir_instance.filter(F(device_role__name__contains="switch")) # Create New Interfaces result = filtered_inventory.run(task=create_netbox_interfaces, nb_interfaces=nb_interfaces, netbox=netbox) print_result(result) # Update Existing Interfaces result = filtered_inventory.run(task=update_netbox_interfaces, nb_interfaces=nb_interfaces, netbox=netbox) print_result(result)
def main(): VLAN_ID = "123" VLAN_NAME = "ntp_vlan" 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=VLAN_ID, vlan_name=VLAN_NAME) print_result(result)
def main() -> None: nr = InitNornir(config_file="config.yml") result = nr.run(task=dev_info) print_result(result) #End timer end = time.time() #Difference between when the script started and ended delta = end - start print("Time took to execute: " + str(delta))
def get_interface_utilization(interface_dict, interval, duration, host="all"): nr = InitNornir(config_file="config-topo_snmp.yaml") if host != "all": nr = nr.filter(name=host) for i in range(int(duration / interval)): results = nr.run(task=get_interface_stats, interface_dict=interface_dict) time.sleep(interval) print_result(results)
def main() -> None: nr = InitNornir(config_file="h:/Scripts/TEXTFSM/config.yaml") result = nr.run(task=get_facts) print_result(result) nr = InitNornir(config_file="h:/Scripts/TEXTFSM/config.yaml") result1 = nr.run(netmiko_send_command, command_string="write me") print_result(result1)
def main(): with InitNornir(config_file="config_b.yaml") as nr: nr = nr.filter(F(groups__contains="nxos")) # Transform functions are overly complicated in 3.x...just do it yourself for host in nr.inventory.hosts.values(): transform_ansible_inventory(host) agg_result = nr.run(task=napalm_get, getters=["facts"]) print_result(agg_result)
def main(): nr = InitNornir(config_file="config.yaml", logging={"enabled": False}) # result = nr.run(task=my_task) # print_result(result) nr = nr.filter(name="arista1") result = nr.run(task=new_task) # import pdbr # pdbr.set_trace() print_result(result)
def copy_cert(self): nr = cnaas_init() nr_filtered = nr.filter(name=self.testdata['copycert_hostname']) nrresult = nr_filtered.run( task=arista_copy_cert ) if nrresult.failed: print_result(nrresult) self.assertFalse(nrresult.failed, "Task arista_copy_cert returned failed status")
def main(): if OUTPUT_DIR.is_dir(): shutil.rmtree(OUTPUT_DIR) OUTPUT_DIR.mkdir(parents=True, exist_ok=True) with InitNornir(config_file="nr-config-local.yaml") as nr: # results = nr.run(task=save_nc_get_config) # print_result(results) results = nr.run(task=edit_nc_config_from_yaml) print_result(results)
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)
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()
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)
def configure_snmp(): nr = InitNornir(config_file="config-topo_snmp.yaml") cfg = ['snmp-server community public RO', 'snmp-server community private RW'] cfg_snmp_v3 = [ 'snmp-server view MyTestView iso included', 'snmp-server group DevNetSNMPGroup v3 priv read MyTestView', 'snmp-server user devnet_snmp_user DevNetSNMPGroup v3 auth sha 4S3cr3tP4$$ priv aes 128 pr1vP@ss'] result = nr.run( task=netmiko_send_config, config_commands=cfg_snmp_v3 ) print_result(result)
def main(): p = argparse.ArgumentParser() p.add_argument("--hosts", nargs="+", help="Target host") p.add_argument("--check", action="store_true", help="Enable check mode") args = p.parse_args() nr = InitNornir(config_file="nr-config.yml") for host in args.hosts: target_host = nr.filter(name=host) result = target_host.run(task=set_interface, dry_run=args.check) print_result(result)