severity_level=logging.DEBUG, ) tqdm.write(f"{task.host}: BGP config from device complete") progress_bar.update() def process_tasks(task): if task.failed: print_result(task) print("Exiting script before we break anything else!") sys.exit(1) else: print(f"Task {task.name} completed successfully!") nr = InitNornir(config_file="config.yaml", dry_run=False) all_devices = nr.filter(type="juniper") with tqdm(total=len(all_devices.inventory.hosts), desc="Get BGP Config") as progress_bar: deploy_netflow_config = all_devices.run(task=netflow_configuration, progress_bar=progress_bar) process_tasks(deploy_netflow_config) #print_result(deploy_netflow_config) # import ipdb; ipdb.set_trace() def parse_bgp_config(nornir_object): bgp_groups = []
from nornir import InitNornir from nornir.plugins.tasks.networking import netmiko_send_command from nornir.plugins.functions.text import print_result from nornir.core.filter import F import re import sys mac = input("Please, enter MAC address in format: HHHH.HHHH.HHHH").strip() mac = mac.lower() mac_regexp = re.compile(r'[a-f0-9]{4,4}\.[a-f0-9]{4,4}\.[a-f0-9]{4,4}') mac_check = mac_regexp.search(mac) if mac_check == None: print("Wrong MAC address.") sys.exit(1) norn = InitNornir(config_file='norn-config-local.yml') switches = norn.filter(F(groups__contains="switches")) #get mac address tables and cdp neighbours from all switches show_mac = switches.run(task=netmiko_send_command, command_string="show mac address-table", use_textfsm=True) show_cdp_nei = switches.run(task=netmiko_send_command, command_string="show cdp neighbors", use_textfsm=True) show_arp = norn.run(task=netmiko_send_command, command_string="show ip arp", use_textfsm=True) show_int_sw = switches.run(task=netmiko_send_command, command_string="show interfaces switchport", use_textfsm=True) for hostname in show_mac.keys(): for interface in show_mac[hostname][0].result: if interface['destination_address'] == mac:
from nornir import InitNornir from nornir_utils.plugins.functions import print_result from nornir_netmiko import netmiko_send_command from nornir.core.filter import F def hello_world(task): task.run(name='show ip inter brief', task=netmiko_send_command, command_string='show ip inter brief') task.run(name='show bgp sum', task=netmiko_send_command, command_string='show bgp sum') nr = InitNornir(config_file="./config.yml") routers = nr.filter(F(groups__contains="csr1000v")) r = routers.run(hello_world) print_result(r)
from nornir import InitNornir from nornir.plugins.tasks import networking, text from nornir.plugins.functions.text import print_title, print_result nr = InitNornir(config_file="config.yaml", dry_run=True) def hostname_config(task): var = task.run(task=text.template_file, name="Switches hostname configuration", template="hostnames.j2", # current directory: path="templates") task.host["hostname_config"] = var.result task.run( task=networking.netmiko_send_config, name="Configure hostname on the device", config_commands=task.host["hostname_config"], ) def interfaces_config(task): var = task.run(task=text.template_file, name="Switches interface configuration", template="interfaces.j2", # current directory: path="templates") task.host["interfaces_config"] = var.result task.run( networking.netmiko_send_config, name="Loading Configuration on the device", config_commands=task.host["interfaces_config"].splitlines() ) def send_ping(task):
from nornir import InitNornir from nornir_utils.plugins.functions import print_result nr = InitNornir("config.yml") print ("Lists of all hosts in inventory:") print (nr.inventory.hosts)
def main(): nr = InitNornir() eos = nr.filter(F(platform="eos")) results = eos.run(task=file_transfer, num_workers=10) print_result(results)
def main(): nr = InitNornir(config_file="config.yaml") nr = nr.filter(F(groups__contains="eos")) result = nr.run(task=file_copy) print_result(result)
def main(): nr = InitNornir(config_file="config.yaml") nr = nr.filter(F(groups__contains="nxos")) agg_result = nr.run(task=get_checkpoint_file) print_result(agg_result)
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") nr = nr.filter(name="srx2") agg_result = nr.run(task=junos_acl) print_result(agg_result)
def os_upgrade(self, hostname, hostaddr): def get_output(agg_result): for k, multi_result in agg_result.items(): for result_obj in multi_result: return result_obj.result # 'sw_log' function sends syslog messages to the switch. def sw_log(logmsg): result = nr.run( task=netmiko_send_command, command_string=f'send log ZTP-Watcher: {logmsg}', ) return (result) # 'send_cmd' function sends commands to the host. def send_cmd(cmd): result = nr.run( task=netmiko_send_command, command_string=cmd, delay_factor=6, ) return (result) # 'send_config' function sends configuration commands to the host. def send_config(config): result = nr.run(task=netmiko_send_config, config_commands=config) return (result) # Instatiate an SNMP instance def get_SNMP(ip_addr, config): snmp = SNMP(ip_addr, version=3, username=config['snmp_username'], authproto=config['snmp_authproto'], authkey=config['snmp_authkey'], privproto=config['snmp_privproto'], privkey=config['snmp_privkey']) return snmp # Truncates new_ios & boot_ios to versions # That can be accurately compared # Readability > Clever def truncate_ios(new_ios, boot_ios, ios_xe): new_ios_split = new_ios.split('.') new_ios_rstrip = '.' + new_ios_split[-1] new_ios_lstrip = new_ios_split[0] + '.' new_ios = new_ios.rstrip(new_ios_rstrip) new_ios = new_ios.lstrip(new_ios_lstrip) if ios_xe: new_ios = new_ios.rstrip('.SPA') # Would break 03.03, but that is really old new_ios = new_ios.replace('0', '') else: new_ios = new_ios[:2] + '.' + new_ios[2:] boot_ios = boot_ios.replace('(', '-') boot_ios = boot_ios.replace(')', '.') return (boot_ios, new_ios) # Parse out 1.3.6.1.2.1.1.1.0 for version information # Also, determine if it is a 3850 # Help needed - do all IOS XE versions have a CAT3K in them? # Note: 1.3.6.1.2.1.16.19.6.0 boot file is not reliable for ios xe def fetch_ver(snmp): ios_xe = False sysDescr = str(snmp.get('1.3.6.1.2.1.1.1.0')) if 'CAT3K' in sysDescr: ios_xe = True ver = (sysDescr.split(',')) if 'Version' in ver[2]: ver = ver[2].lstrip(' Version ') else: ver = ver[3].lstrip(' Version ').split()[0] return ver, ios_xe # Archive = Run Before Bin = Run After def wr_mem(is_tar=True): sw_log('Writing config.') writemem = send_cmd('write mem') if is_tar: Logger(f'{hostname}: Config written, ready to upgrade.') sw_log('Config written, ready for upgrade.') else: Logger( f'{hostname}: Config written, ready to reload/power off.') sw_log('Config written, ready to reload/power off.') #result = get_output(writemem) # Logger(result) # Uncomment for TS # Only for .bin # This function should properly handle the setting of boot string def set_boot_var(new_ios): sw_log('Setting boot variable and writing config.') bootcmds = f'default boot sys\nboot system flash:{new_ios}' bootcmds_list = bootcmds.splitlines() bootvar = send_config(bootcmds_list) Logger(f'{hostname}: Boot variable set -> write config.') #result = get_output(bootvar) # Logger(result) # Uncomment for TS # IOS XE only - specifically 3850 # This does a software clean def ios_xe_upgrade(copy_method, tftpaddr, new_ios, old_xe=False): if old_xe: cmd = 'software clean' else: cmd = 'request platform software package clean switch all' #DEBUG #Logger(cmd) result = nr.run(task=netmiko_send_command, command_string=cmd, delay_factor=6, expect_string="Nothing|proceed") for device_name, multi_result in result.items(): #DEBUG #Logger(multi_result[0].result) if "proceed" in multi_result[0].result: Logger("Cleaning old software.") result = nr.run(task=netmiko_send_command, command_string='y', delay_factor=6, expect_string=r"\#") else: Logger("No software cleaning required.") Logger('Cleaner Done') ##result = get_output(result) ##Logger(result) # Uncomment for TS # FIXME: Figure out why it won't work without sleep time.sleep(1) cmd = f'copy {copy_method}{tftpaddr}/{new_ios} flash:' #DEBUG Logger(cmd) result = nr.run(task=netmiko_send_command, command_string=cmd, delay_factor=6, expect_string=r'Destination filename') #DEBUG result2 = get_output(result) Logger(result2) # Uncomment for TS for device_name, multi_result in result.items(): Logger(multi_result[0].result) if "Destination" in multi_result[0].result: result = nr.run(task=netmiko_send_command, command_string=new_ios, delay_factor=6, expect_string=r"\#") result2 = get_output(result) Logger(result2) # Uncomment for TS if old_xe: a = (f'software install file flash:{new_ios} on-reboot new') Logger(a) installer = send_cmd(a) else: a = ( 'request platform software package install switch all file ' f'flash:{new_ios} new auto-copy') installer = send_cmd(a) result = get_output(installer) Logger(result) # Uncomment for TS nr = InitNornir( #logging={"file": "debug.txt", "level": "debug"}, inventory={ 'options': { 'hosts': { hostname: { 'hostname': hostaddr, 'username': username, 'password': password, 'platform': 'ios' } } } }) Logger(f'{hostname}: Fetching boot variable via SNMP to compare.') # I need SNMP anyway, and can fetch this in a fraction of the time # it takes to get it via SSH snmp = get_SNMP(hostaddr, config) try: model_oid = str(snmp.get('1.3.6.1.2.1.1.2.0')) except: # FIXME - Maybe Good-er Exception handling and try again after wait Logger(f'{hostname}: Can not SNMP - BAILING!.') sw_log('Error: Can not SNMP.') nr.close_connections() return # Bit Ugly if model_oid in config: new_ios = config[model_oid] is_tar = new_ios.split('.')[-1] == 'tar' if is_tar: wr_mem() boot_ios, ios_xe = fetch_ver(snmp) boot_ios_tr, new_ios_tr = truncate_ios(new_ios, boot_ios, ios_xe) if boot_ios_tr == new_ios_tr: Logger( f'{hostname}: Up to date ({boot_ios_tr}), skipping transfer.' ) sw_log( f'Image file ({boot_ios_tr}) up to date, skipping transfer.' ) else: copy_method = config['copy_method'] Logger( f'{hostname}: Image old, starting {copy_method.split(":")[0]} transfer.' ) sw_log( f'Newer Version ({new_ios_tr}) exists, starting image transfer via {copy_method.split(":")[0]}.' ) copystart = time.time() if ios_xe: ios_xe_upgrade(copy_method, tftpaddr, new_ios, old_xe=boot_ios_tr.startswith('03')) copyduration = round(time.time() - copystart) Logger( f'{hostname}: Image transfer completed after {copyduration}s.' ) if not is_tar: # sw_log('Image transfer complete.') else: if is_tar: copyfile = send_cmd( f'archive download-sw /over /rel {copy_method}{tftpaddr}/{new_ios}' ) else: copyfile = send_cmd( f'copy {copy_method}{tftpaddr}/{boot_file} flash:') copyduration = round(time.time() - copystart) Logger( f'{hostname}: Image transfer completed after {copyduration}s.' ) if not is_tar: # sw_log('Image transfer complete.') #result = get_output(copyfile) # Logger(result) # Uncomment for TS else: Logger(f'{model_oid}: Not found in config - skipping IOS.') if not is_tar: if not ios_xe: set_boot_var(new_ios) wr_mem(is_tar) Logger(f'Configuration Finished.') sw_log('Config finished, ready to use.') nr.close_connections()
__author__ = 'Petr Ankudinov' from nornir import InitNornir from nornir_napalm.plugins.tasks import napalm_get from nornir_utils.plugins.functions import print_result from nornir_utils.plugins.tasks.files import write_file from nornir_napalm.plugins.tasks import napalm_cli import json import os import re from getpass import getpass from time import time as time from datetime import datetime as datetime nr = InitNornir(config_file='config.yaml') def time_stamp(): """ time_stamp function returns current system time as Y-M-D H-M-S string Args: no arguments required Returns: str: current system time as Y-M-D H-M-S string """ time_not_formatted = time() time_formatted = datetime.fromtimestamp(time_not_formatted).strftime( '%Y-%m-%d:%H:%M:%S.%f')
def main() -> None: nr = InitNornir() result = nr.run(task=dev_info) print_result(result)
from nornir.plugins.functions.text import print_result from nornir.plugins.tasks.files import write_file from datetime import date import pathlib from nornir.plugins.tasks.networking import netmiko_send_command 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()) command_dir = date_dir + "/" + cmd pathlib.Path(config_dir).mkdir(exist_ok=True) pathlib.Path(date_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", ) nr = InitNornir(config_file="/Users/stephenamaki/Dropbox/netdevops/nornir/config.yaml") target_hosts = nr.filter(role="core") result = target_hosts.run(name="Creating Backup Archive", task=backup_configurations) print_result(result)
import pdbr # noqa from nornir import InitNornir from nornir.core.filter import F from nornir_utils.plugins.functions import print_result # noqa def netmiko_direct(task): # Manually create Netmiko connection host_obj = task.host net_connect = host_obj.get_connection("netmiko", task.nornir.config) print(net_connect.find_prompt()) # pdbr.set_trace() print(host_obj.connections) host_obj.close_connection("netmiko") print(host_obj.connections) if __name__ == "__main__": # Use a context-manager so connections are gracefully closed with InitNornir(config_file="config.yaml") as nr: ios_filt = F(groups__contains="ios") nr_ios = nr.filter(ios_filt) nr_ios.run(task=netmiko_direct) # pdbr.set_trace() # pdbr.set_trace()
def main(): nr = InitNornir() nr.run(task=my_task)
def main(): nr = InitNornir(config_file="config.yaml") nr = nr.filter(name="c3560") agg_result = nr.run(task=networking.netmiko_send_command, command_string="show run | i hostname") print(agg_result["c3560"].result)
def main(): nr = InitNornir(config_file="../../config.yaml") results = nr.run(task=check_uptime)
""" inventory_dict = yaml.safe_load(inventory_data) NornirObj = InitNornir( runner={ "plugin": "RetryRunner", "options": { "num_workers": 100, "num_connectors": 10, "connect_retry": 3, "connect_backoff": 1000, "connect_splay": 100, "task_retry": 3, "task_backoff": 1000, "task_splay": 100, }, }, inventory={ "plugin": "DictInventory", "options": { "hosts": inventory_dict["hosts"], "groups": inventory_dict["groups"], "defaults": inventory_dict.get("defaults", {}), }, }, ) def test_FB(): res = FFun(NornirObj, FB="R[12]")
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)
def main(): nr = InitNornir(config_file="config.yaml", logging={"enabled": False}) nr = nr.filter(name="srx2") nr.run(task=my_task)
def main(): nr = InitNornir(config_file="config.yaml") print(f"\nNumber of workers: {nr.config.core.num_workers}\n")
def main(): nr = InitNornir(config_file="config.yaml") nr = nr.filter(name="srx2") agg_result = nr.run(task=send_command) print_result(agg_result)
from nornir import InitNornir nr = InitNornir() print(f"{nr.config.core.num_workers}")
def cli(ctx, config): ctx.obj = InitNornir(config_file=config)
from nornir_utils.plugins.functions import print_result from nornir_utils.plugins.tasks.files import write_file from nornir_napalm.plugins.tasks import * from nornir_netmiko.tasks import * from nornir_jinja2.plugins.tasks import * from nornir_netbox.plugins.inventory import NetBoxInventory2 from mytasks import * from mytasks.batfishTasks import * InventoryPluginRegister.register("SerialRunner", SerialRunner) InventoryPluginRegister.register("ThreadedRunner", ThreadedRunner) InventoryPluginRegister.register("NetBoxInventory2", NetBoxInventory2) nr = InitNornir( config_file='config.yaml', dry_run=False) nr = nr.filter(name = 'localhost') def batfish_tasks(task): task.run( task = BF_session, host = "localhost", ) task.run( task = BF_init, network_name = 'forwarding_change_validation', snapshot_name = 'base',
from nornir import InitNornir from nornir.plugins.functions.text import print_result, print_title from nornir.plugins.tasks.networking import netmiko_send_command, netmiko_send_config import getpass nr = InitNornir(config_file="config.yaml") username = input("Please enter domain username: "******"show cdp neighbor", use_genie=True) task.host["facts"] = r.result outer = task.host["facts"] indexer = outer['cdp']['index'] for idx in indexer: local_intf = indexer[idx]['local_interface'] remote_port = indexer[idx]['port_id'] remote_id = indexer[idx]['device_id'] cdp_config = task.run( netmiko_send_config, name="Automating CDP Network Descriptions", config_commands=[ "interface " + str(local_intf), "description Connected to " + str(remote_id) + " via its " + str(remote_port) + " interface" ])
def main(): nr = InitNornir(config_file='config.yaml') gc_targets = nr.filter(F(groups__contains='glasgownet') & F(groups__contains='core')) result = gc_targets.run(task=get_input) print_result(result, severity_level=logging.WARNING)
def main(): nr = InitNornir() sfo = nr.filter(F(groups__contains="sfo")) print(sfo.inventory.hosts)
def main(): nr = InitNornir() print(nr.inventory.hosts["arista3"].items()) print(nr.inventory.hosts["arista3"].data)