def main(): # Use the appropriate network driver to connect to the device: driver = napalm.get_network_driver('nxos') # Connect: device = driver(hostname='192.168.2.3', username='******', password='******') print 'Opening ...' device.open() config_string = """ interface Ethernet1/20 no switchport ip address 172.16.1.1/24 """ device.load_merge_candidate(config=config_string) # Note that the changes have not been applied yet. Before applying # the configuration you can check the changes: print '\nDiff:' print device.compare_config() # You can commit or discard the candidate changes. choice = raw_input("\nWould you like to commit these changes? [yN]: ") if choice == 'y': print 'Committing ...' device.commit_config() else: print 'Discarding ...' device.discard_config() # close the session with the device. device.close() print 'Done.'
def __init__(self): """Initialise new instance.""" if not isinstance(self.driver_class, NetworkDriver): if type(self).name: self.driver_class = napalm.get_network_driver(type(self).name) else: raise ValueError
def run(vendor, hostname, user, password, strategy, optional_args, config_file, dry_run): logger.debug('Getting driver for OS "{driver}"'.format(driver=vendor)) driver = get_network_driver(vendor) if optional_args is not None: optional_args = {x.split('=')[0]: x.split('=')[1] for x in optional_args.replace(' ', '').split(',')} logger.debug('Connecting to device "{device}" with user "{user}" and optional_args={optional_args}'.format( device=hostname, user=user, optional_args=optional_args)) with driver(hostname, user, password, optional_args=optional_args) as device: logger.debug('Strategy for loading configuration is "{strategy}"'.format(strategy=strategy)) if strategy == 'replace': strategy_method = device.load_replace_candidate elif strategy == 'merge': strategy_method = device.load_merge_candidate logger.debug('Loading configuration file "{config}"'.format(config=config_file)) strategy_method(filename=config_file) logger.debug('Comparing configuration') diff = device.compare_config() if dry_run: logger.debug('Dry-run. Discarding configuration.') else: logger.debug('Committing configuration') device.commit_config() logger.debug('Closing session') return diff
def napalm(self, request, pk): """ Execute a NAPALM method on a Device """ device = get_object_or_404(Device, pk=pk) if not device.primary_ip: raise ServiceUnavailable("This device does not have a primary IP address configured.") if device.platform is None: raise ServiceUnavailable("No platform is configured for this device.") if not device.platform.napalm_driver: raise ServiceUnavailable("No NAPALM driver is configured for this device's platform ().".format( device.platform )) # Check that NAPALM is installed and verify the configured driver try: import napalm from napalm_base.exceptions import ConnectAuthError, ModuleImportError except ImportError: raise ServiceUnavailable("NAPALM is not installed. Please see the documentation for instructions.") try: driver = napalm.get_network_driver(device.platform.napalm_driver) except ModuleImportError: raise ServiceUnavailable("NAPALM driver for platform {} not found: {}.".format( device.platform, device.platform.napalm_driver )) # Verify user permission if not request.user.has_perm('dcim.napalm_read'): return HttpResponseForbidden() # Validate requested NAPALM methods napalm_methods = request.GET.getlist('method') for method in napalm_methods: if not hasattr(driver, method): return HttpResponseBadRequest("Unknown NAPALM method: {}".format(method)) elif not method.startswith('get_'): return HttpResponseBadRequest("Unsupported NAPALM method: {}".format(method)) # Connect to the device and execute the requested methods # TODO: Improve error handling response = OrderedDict([(m, None) for m in napalm_methods]) ip_address = str(device.primary_ip.address.ip) d = driver( hostname=ip_address, username=settings.NAPALM_USERNAME, password=settings.NAPALM_PASSWORD, timeout=settings.NAPALM_TIMEOUT, optional_args=settings.NAPALM_ARGS ) try: d.open() for method in napalm_methods: response[method] = getattr(d, method)() except Exception as e: raise ServiceUnavailable("Error connecting to the device at {}: {}".format(ip_address, e)) d.close() return Response(response)
def setUp(self): initial_config = '{}/initial.conf'.format(self.vendor) driver = get_network_driver(self.vendor) device = driver(self.hostname, self.username, self.password, timeout=60, optional_args=self.optional_args) device.open() device.load_replace_candidate(filename=initial_config) device.commit_config() device.close()
def bgp_neighbors(self): """Get BGP session info using napalm.""" try: driver_name = self.device_driver except AttributeError: driver_name = settings.DEFAULT_DRIVER driver = napalm.get_network_driver(driver_name) with driver(hostname=self.hostname, username=settings.NAPALM_USERNAME, password=settings.NAPALM_PASSWORD) as device: neighbors = device.get_bgp_neighbors() return neighbors
def setUpClass(cls): username = '******' ip_addr = raw_input("Enter device ip or hostname: ") ip_addr = ip_addr.strip() password = getpass() cls.vendor = 'ios' driver = get_network_driver(cls.vendor) optional_args = {} optional_args['dest_file_system'] = 'flash:' cls.device = driver(ip_addr, username, password, optional_args=optional_args) cls.device.open()
def main(default="config.cfg", username="******", password="******", switch="switch.cfg"): """Open the device, merge the config and commit it.""" driver = get_network_driver('junos') creds_dict = {username: password} device = open_device(switch, driver, creds_dict) if device: make_changes(device, default) device.close() print("{0} is closed".format(device.hostname)) else: print("Sionara!")
def setUpClass(cls): ip_addr = '127.0.0.1' username = '******' password = '******' cls.vendor = 'ios' driver = get_network_driver(cls.vendor) optional_args = {'port': 12204, 'dest_file_system': 'bootflash:'} cls.device = driver(ip_addr, username, password, optional_args=optional_args) cls.device.open() # Setup initial state cls.device.load_replace_candidate(filename='%s/initial.conf' % cls.vendor) cls.device.commit_config()
def main(): module = AnsibleModule( argument_spec=dict( hostname=dict(type='str', required=True), username=dict(type='str', required=True), password=dict(type='str', required=True, no_log=True), timeout=dict(type='int', required=False, default=60), optional_args=dict(required=False, type='dict', default=None), config_file=dict(type='str', required=False), config_str=dict(type='str', required=False), dev_os=dict(type='str', required=True, choices=['eos', 'junos', 'iosxr', 'fortios', 'ibm', 'ios', 'nxos']), commit_changes=dict(type='bool', required=True), replace_config=dict(type='bool', required=False, default=False), diff_file=dict(type='str', required=False, default=None), get_diffs=dict(type='bool', required=False, default=True) ), supports_check_mode=True ) if not napalm_found: module.fail_json(msg="the python module napalm is required") hostname = module.params['hostname'] username = module.params['username'] dev_os = module.params['dev_os'] password = module.params['password'] timeout = module.params['timeout'] config_file = module.params['config_file'] config_str = module.params['config_str'] commit_changes = module.params['commit_changes'] replace_config = module.params['replace_config'] diff_file = module.params['diff_file'] get_diffs = module.params['get_diffs'] if module.params['optional_args'] is None: optional_args = {} else: optional_args = module.params['optional_args'] try: network_driver = get_network_driver(dev_os) device = network_driver(hostname=hostname, username=username, password=password, timeout=timeout, optional_args=optional_args) device.open() except Exception, e: module.fail_json(msg="cannot connect to device: " + str(e))
def get_arista_lldp(device, username, password): """ use napalm to get the lldp neighbors for all the swtiches :param device: :param username: :param password: :return: """ driver = get_network_driver('eos') deviceAPI = driver(device, username, password) deviceAPI.open() result = {'neighbors': deviceAPI.get_lldp_neighbors_detail(), 'address': device} return result
def get_arista_mac_table(device, username, password): """ use napalm to get the mac address table :param device: :param username: :param password: :return: dict of results """ driver = get_network_driver('eos') deviceAPI = driver(device, username, password) deviceAPI.open() result = {'macs': deviceAPI.get_mac_address_table(), 'address': device} return result
def setUpClass(cls): """Executed when the class is instantiated.""" cls.mock = True username = '******' ip_addr = '192.168.0.234' password = '******' cls.vendor = 'ios' driver = get_network_driver(cls.vendor) optional_args = {} optional_args['dest_file_system'] = 'flash:' cls.device = driver(ip_addr, username, password, optional_args=optional_args) if cls.mock: cls.device.device = FakeIOSDevice() else: cls.device.open()
def main(config_file): """Load a config for the device.""" if not (os.path.exists(config_file) and os.path.isfile(config_file)): msg = 'Missing or invalid config file {0}'.format(config_file) raise ValueError(msg) print('Loading config file {0}.'.format(config_file)) # Use the appropriate network driver to connect to the device: driver = napalm.get_network_driver('eos') # Connect: device = driver(hostname='127.0.0.1', username='******', password='******', optional_args={'port': 12443}) print('Opening ...') device.open() print('Loading replacement candidate ...') device.load_replace_candidate(filename=config_file) # Note that the changes have not been applied yet. Before applying # the configuration you can check the changes: print('\nDiff:') print(device.compare_config()) # You can commit or discard the candidate changes. try: choice = raw_input("\nWould you like to commit these changes? [yN]: ") except NameError: choice = input("\nWould you like to commit these changes? [yN]: ") if choice == 'y': print('Committing ...') device.commit_config() else: print('Discarding ...') device.discard_config() # close the session with the device. device.close() print('Done.')
def main(config_file): """Load a config for the device.""" if not (os.path.exists(config_file) and os.path.isfile(config_file)): msg = "Missing or invalid config file {0}".format(config_file) raise ValueError(msg) print "Loading config file {0}.".format(config_file) # Use the appropriate network driver to connect to the device: driver = napalm.get_network_driver("eos") # Connect: device = driver(hostname="127.0.0.1", username="******", password="******", optional_args={"port": 12443}) print "Opening ..." device.open() print "Loading replacement candidate ..." device.load_replace_candidate(filename=config_file) # Note that the changes have not been applied yet. Before applying # the configuration you can check the changes: print "\nDiff:" print device.compare_config() # You can commit or discard the candidate changes. choice = raw_input("\nWould you like to commit these changes? [yN]: ") if choice == "y": print "Committing ..." device.commit_config() else: print "Discarding ..." device.discard_config() # close the session with the device. device.close() print "Done."
def get_arista(device, username, password): """ use eapi to discover a device :param device: :param username: :param password: :return: dict of results """ driver = get_network_driver('eos') device_api = driver(device, username, password) device_api.open() result = device_api.get_facts() result.update({'address': device}) interfaces = result.pop('interface_list') device_obj, created = Device.objects.update_or_create(address=device, defaults=result) for interface in interfaces: interface_obj, created = Interface.objects.update_or_create(device=device_obj, name=interface)
def interfaces(ip, username, password, ios): driver = get_network_driver(ios) with driver(ip, username, password) as device: info = device.get_interfaces() return info
from napalm import get_network_driver import json driver = get_network_driver('ios') optional_args = {'secret': 'cisco'} #cisco is the enable password ios = driver('10.1.1.10', 'andrei', 'cisco', optional_args=optional_args) ios.open() #start your code output = ios.get_arp_table() # for item in output: # print(item) dump = json.dumps(output, sort_keys=True, indent=4) #print(dump) with open('arp.txt', 'w') as f: f.write(dump) #end your code ios.close()
] for host in hosts: if not ping.py_ping(host['host']): print(host['host'], ' is unreachable!!') continue print('=' * 60) print('''host : {} vendor : {} admin_port: {} '''.format(host['host'], host['vendor'], host['port'])) if host['vendor'] == 'cisco': driver = napalm.get_network_driver('ios') optional_args = { 'transport': '{}'.format(host['port']), } node = driver('{}'.format(host['host']), 'user', 'cisco', optional_args=optional_args) node.open() print(json.dumps(node.get_arp_table(), indent=4), '\n') node.close() if host['vendor'] == 'huawei': driver = napalm.get_network_driver('ce') optional_args = { 'transport': '{}'.format(host['port']), }
def main(): module = AnsibleModule(argument_spec=dict( hostname=dict(type='str', required=False, aliases=['host']), username=dict(type='str', required=False), password=dict(type='str', required=False, no_log=True), provider=dict(type='dict', required=False), timeout=dict(type='int', required=False, default=60), optional_args=dict(required=False, type='dict', default=None), config_file=dict(type='str', required=False), config=dict(type='str', required=False), dev_os=dict(type='str', required=False), commit_changes=dict(type='bool', required=True), replace_config=dict(type='bool', required=False, default=False), diff_file=dict(type='str', required=False, default=None), get_diffs=dict(type='bool', required=False, default=True), archive_file=dict(type='str', required=False, default=None), candidate_file=dict(type='str', required=False, default=None)), supports_check_mode=True) if not napalm_found: module.fail_json(msg="the python module napalm is required") provider = module.params['provider'] or {} no_log = ['password', 'secret'] for param in no_log: if provider.get(param): module.no_log_values.update(return_values(provider[param])) if provider.get('optional_args') and provider['optional_args'].get( param): module.no_log_values.update( return_values(provider['optional_args'].get(param))) if module.params.get( 'optional_args') and module.params['optional_args'].get(param): module.no_log_values.update( return_values(module.params['optional_args'].get(param))) # allow host or hostname provider['hostname'] = provider.get('hostname', None) or provider.get( 'host', None) # allow local params to override provider for param, pvalue in provider.items(): if module.params.get(param) is not False: module.params[param] = module.params.get(param) or pvalue hostname = module.params['hostname'] username = module.params['username'] dev_os = module.params['dev_os'] password = module.params['password'] timeout = module.params['timeout'] config_file = module.params['config_file'] config = module.params['config'] commit_changes = module.params['commit_changes'] replace_config = module.params['replace_config'] diff_file = module.params['diff_file'] get_diffs = module.params['get_diffs'] archive_file = module.params['archive_file'] candidate_file = module.params['candidate_file'] argument_check = { 'hostname': hostname, 'username': username, 'dev_os': dev_os } for key, val in argument_check.items(): if val is None: module.fail_json(msg=str(key) + " is required") if module.params['optional_args'] is None: optional_args = {} else: optional_args = module.params['optional_args'] try: network_driver = get_network_driver(dev_os) except ModuleImportError as e: module.fail_json(msg="Failed to import napalm driver: " + str(e)) try: device = network_driver(hostname=hostname, username=username, password=password, timeout=timeout, optional_args=optional_args) device.open() except Exception as e: module.fail_json(msg="cannot connect to device: " + str(e)) try: if archive_file is not None: running_config = device.get_config(retrieve="running")["running"] save_to_file(running_config, archive_file) except Exception as e: module.fail_json(msg="cannot retrieve running config:" + str(e)) try: if replace_config and config_file: device.load_replace_candidate(filename=config_file) elif replace_config and config: device.load_replace_candidate(config=config) elif not replace_config and config_file: device.load_merge_candidate(filename=config_file) elif not replace_config and config: device.load_merge_candidate(config=config) else: module.fail_json( msg="You have to specify either config or config_file") except Exception as e: module.fail_json(msg="cannot load config: " + str(e)) try: if get_diffs: diff = device.compare_config() changed = len(diff) > 0 else: changed = True diff = None if diff_file is not None and get_diffs: save_to_file(diff, diff_file) except Exception as e: module.fail_json(msg="cannot diff config: " + str(e)) try: if candidate_file is not None: running_config = device.get_config( retrieve="candidate")["candidate"] save_to_file(running_config, candidate_file) except Exception as e: module.fail_json(msg="cannot retrieve running config:" + str(e)) try: if module.check_mode or not commit_changes: device.discard_config() else: if changed: device.commit_config() except Exception as e: module.fail_json(msg="cannot install config: " + str(e)) try: device.close() except Exception as e: module.fail_json(msg="cannot close device connection: " + str(e)) module.exit_json(changed=changed, msg=diff)
from napalm import get_network_driver import os import shutil import re from datetime import datetime import mynapalmfunctions ipaddr = input("What is the IP-Address?") username = input("What is the username?") password = input("What is the password?") # with junos_driver(**junos_device) as junos: # version = junos.cli(command="show system version") # print(version) junos_driver = get_network_driver('junos') junos_device = {'username': username, 'password': password, 'hostname': ipaddr} with junos_driver(**junos_device) as junos: shrun = junos.get_config() with junos_driver(**junos_device) as junos: interfaces = junos.get_interfaces() log = ['show log'] with junos_driver(**junos_device) as junos: logs = junos.cli(log) commands = ['show version', 'show chassis hardware'] #These commands have the serial # + model #, just need to parse the data
from napalm import get_network_driver # import code from NAPALM driver = get_network_driver('eos') # get hte driver for Arista devices device = driver('172.16.2.20', 'admin', 'alta3') # apply the switch credentials device.open() # start the connection device.rollback()
from napalm import get_network_driver import json cisco_ip = [ "SWITCH2", "SWITCH3", "SWITCH4", "SWITCH5", ] for ip in cisco_ip: print("********************************* " + ip + " *********************************") DRV = get_network_driver('ios') cisco_device = DRV(ip, 'john', 'ipvzero') cisco_device.open() response = cisco_device.get_bgp_neighbors() dump_output = json.dumps(response, indent=4) print(dump_output) arista_ip = [ "SWITCH6", "SWITCH7", "SWITCH8", ] for ip in arista_ip: print("********************************** " + ip + " ***********************************") DRV = get_network_driver('eos')
# Create users users = [] user_list_ids = [155] user_list_ids.extend(range(1, total_users + 1)) for x in user_list_ids: lab_username = '******'.format(user_prefix, x) lab_password = ''.join( random.choices(string.ascii_uppercase, k=3) + random.choices(string.ascii_lowercase, k=3) + random.choices(string.digits, k=2)) users.append({'id': x, 'username': lab_username, 'password': lab_password}) print(users) # Configure physical devices driver_ios = napalm.get_network_driver('ios') routers = { 'Router1': { 'device': driver_ios(hostname='172.25.82.12', username=napalm_usernamne, password=napalm_password, optional_args={'port': 22}), 'ip': 12 }, 'Router2': { 'device': driver_ios(hostname='172.25.82.13', username=napalm_usernamne,
def _mock_get_network_driver(self, monkeypatch): mock_driver = napalm.get_network_driver("mock") monkeypatch.setattr(importer_napalm, "get_network_driver", lambda *args: mock_driver)
def func_call(obj): try: print(json.dumps(obj(), sort_keys=True, indent=4)) except (IOError, KeyError, NameError, NotImplementedError) as e: print(f"oops, looks like there is a NAPALM exception, error: {e}") except: print(f"oops, looks like there is an exception") for device_type, device in devices.items(): print( f"\n----- connecting to device {device_type}: {device['ip']} ----------" ) driver = napalm.get_network_driver(device_type) if device_type == NXOS: napalm_device = driver( hostname=device["ip"], username=device["username"], password=device["password"], ) else: napalm_device = driver( hostname=device["ip"], username=device["username"], password=device["password"], optional_args={"port": device["port"]}, )
def parse_args(cli_args): parser = ArgumentParser(description='Starts a plugin using NAPALM ' 'for the specified device') parser.add_argument('driver', help='The driver to run', choices=napalm.SUPPORTED_DRIVERS, type=str) parser.add_argument('--hostname', help='The hostname of the device', type=str) parser.add_argument('-u', '--username', help='The username of the device', type=str) parser.add_argument('-p', '--password', dest='password', type=str, help='The password of the device') parser.add_argument('-t', '--timeout', type=int, help='Timeout for the device', default=60) parser.add_argument( '-d', '--device-config', dest='device_config', type=str, help='The configuration to use for the device (overrides CLI)') parser.add_argument('--bg-host', dest='bg_host', type=str, help='The hostname for Beer Garden', default='localhost') parser.add_argument('--bg-port', dest='bg_port', type=int, help='The port for Beer Garden', default=2337) parser.add_argument('--ssl', help='Beer Garden SSL Enabled flag', action='store_true', default=False) parser.add_argument('--ca-cert', help='Certificate Authority to use', dest='ca_cert', type=str, default=None) parser.add_argument('--client-cert', help='Client certificate to use for ' 'beer-garden connection', dest='client_cert', type=str, default=None) parser.add_argument('--plugin-name', help='Plugin Name to use defaults to ' '(${driver}-plugin)', type=str, dest='plugin_name') parser.add_argument('--ca-verify', help='Verify the beer-garden certificate', dest='ca_verify', action='store_true', default=False) parser.add_argument('-b', '--bg-config', help='Path to beer-garden config ' '(overrides CLI options)', dest='bg_config', type=str) args_to_return = vars(parser.parse_args(cli_args)) if args_to_return['device_config']: with open(args_to_return['device_config']) as device_config: args_to_return.update(json.load(device_config)) if args_to_return['bg_config']: with open(args_to_return['bg_config']) as bg_config: args_to_return.update(json.load(bg_config)) if not args_to_return['plugin_name']: args_to_return['plugin_name'] = args_to_return['driver'] + '-plugin' required_items = [ 'hostname', 'username', 'password', 'timeout', 'bg_host', 'bg_port', 'ssl', 'ca_cert', 'client_cert', 'plugin_name', 'ca_verify' ] for item in required_items: if item not in args_to_return: print("No %s provided." % item) sys.exit(1) return { 'driver': napalm.get_network_driver(args_to_return['driver']), 'hostname': args_to_return['hostname'], 'username': args_to_return['username'], 'password': args_to_return['password'], 'timeout': args_to_return['timeout'], 'optional_args': args_to_return.get('optional_args', {}), }, { 'bg_host': args_to_return['bg_host'], 'bg_port': args_to_return['bg_port'], 'ssl_enabled': args_to_return['ssl'], 'ca_cert': args_to_return['ca_cert'], 'client_cert': args_to_return['client_cert'], 'name': args_to_return['plugin_name'], 'description': 'Command and control for %s ' 'device' % args_to_return['driver'], 'ca_verify': args_to_return['ca_verify'], 'version': napalm.__version__, }
from napalm import get_network_driver import json import urllib3 driver = get_network_driver('nxos') #optional_args = {'secret': 'cisco'} #cisco is in the "enable password" ios = driver('10.233.30.3', 'admin', 'WWTwwt1!') ios.open() #start code ips = '10.233.30.1', '10.233.30.3' for output in ips: ios.ping(output) #output = ios.ping('10.233.30.1') dump = json.dumps(output, sort_keys=True, indent=4) with open('ping_table.txt', 'w') as f: f.write(dump) ping_j = open("ping_table.txt") read_ping = ping_j.read() success_ping = json.loads(read_ping) print(success_ping) #end your code ios.close()
def get_onboarding_facts(self): """Gather information from the network device that is needed to onboard the device into the NetBox system. Raises: OnboardException('fail-login'): When unable to login to device OnboardException('fail-execute'): When unable to run commands to collect device information OnboardException('fail-general'): Any other unexpected device comms failure. """ self.check_reachability() logger.info("COLLECT: device information %s", self.hostname) try: # Get Napalm Driver with Netmiko if needed self.set_napalm_driver_name() # Raise if no Napalm Driver not selected self.check_napalm_driver_name() driver = get_network_driver(self.napalm_driver) optional_args = self.optional_args.copy() if self.port: optional_args["port"] = self.port if self.secret: optional_args["secret"] = self.secret napalm_device = driver( hostname=self.hostname, username=self.username, password=self.password, timeout=self.timeout, optional_args=optional_args, ) napalm_device.open() logger.info("COLLECT: device facts") self.facts = napalm_device.get_facts() logger.info("COLLECT: device interface IPs") self.ip_ifs = napalm_device.get_interfaces_ip() module_name = PLUGIN_SETTINGS["onboarding_extensions_map"].get(self.napalm_driver) if module_name and self.load_driver_extension: try: module = importlib.import_module(module_name) driver_addon_class = module.OnboardingDriverExtensions(napalm_device=napalm_device) self.onboarding_class = driver_addon_class.onboarding_class self.driver_addon_result = driver_addon_class.ext_result except ModuleNotFoundError as exc: raise OnboardException( reason="fail-general", message=f"ERROR: ModuleNotFoundError: Onboarding extension for napalm driver {self.napalm_driver} configured but can not be imported per configuration", ) except ImportError as exc: raise OnboardException(reason="fail-general", message="ERROR: ImportError: %s" % exc.args[0]) else: logger.info( "INFO: No onboarding extension defined for napalm driver %s, using default napalm driver", self.napalm_driver, ) except ConnectionException as exc: raise OnboardException(reason="fail-login", message=exc.args[0]) except CommandErrorException as exc: raise OnboardException(reason="fail-execute", message=exc.args[0]) except Exception as exc: raise OnboardException(reason="fail-general", message=str(exc))
from napalm import get_network_driver from pprint import pprint # from pprint import pprint driver_ios = get_network_driver('ios') sw1 = driver_ios('10.0.0.1', 'user', 'password') sw1.open() #Get list of interfaces and IOS version and such sw1_output = sw1.get_facts() pprint(sw1_output) #Get more info of interfaces sw1_output = sw1.get_interfaces() pprint(sw1_output) #Get ARP address table sw1_output = sw1.get_arp_table() pprint(sw1_output) # List of all the things you can retrive by get # https://napalm.readthedocs.io/en/latest/support/index.html
def main(): dev_name = args.dev_name driver = get_network_driver("junos") optional_args = {"allow_agent": "True", "use_keys": "True"} device = driver(args.dev_name, args.username, "", optional_args=optional_args) device.open() print(f"Getting interface list from {args.dev_name}") interfaces = device.get_interfaces_ip() device.close() v4_ints = {} v6_ints = {} v4_ips_to_check = [] v4_ips_to_update = [] v4_ip_update = {} v6_ips_to_check = [] v6_ips_to_update = [] v6_ip_update = {} ignore_ints = "bme|em1|em2|jsrv|lo" # create new dictionay with just interface as key and ip,mask,form_factor as list of values for k, v in interfaces.items(): for family, address in v.items(): for a, b in address.items(): for x, y in b.items(): if family == "ipv4": if not re.search(ignore_ints, k): if "xe-" in k: v4_ints.update({ k.replace(".0", ""): [ str(a) + "/" + str(y), "1200", ] }) elif "ae" in k: v4_ints.update({ k.replace(".0", ""): [ str(a) + "/" + str(y), "200", ] }) elif "irb" in k: v4_ints.update({ k.replace(".0", ""): [str(a) + "/" + str(y), "0"] }) elif "ge" in k: v4_ints.update({ k.replace(".0", ""): [ str(a) + "/" + str(y), "1000", ] }) elif "et" in k: v4_ints.update({ k.replace(".0", ""): [ str(a) + "/" + str(y), "1400", ] }) elif family == "ipv6": if not re.search(ignore_ints, k): if "2604" in a: if "xe-" in k: v6_ints.update({ k.replace(".0", ""): [ str(a) + "/" + str(y), "1200", ] }) elif "ae" in k: v6_ints.update({ k.replace(".0", ""): [ str(a) + "/" + str(y), "200", ] }) elif "irb" in k: v6_ints.update({ k.replace(".0", ""): [ str(a) + "/" + str(y), "0", ] }) elif "ge" in k: v6_ints.update({ k.replace(".0", ""): [ str(a) + "/" + str(y), "1000", ] }) elif "et" in k: v6_ints.update({ k.replace(".0", ""): [ str(a) + "/" + str(y), "1400", ] }) # Get netbox device ID dev_id = nb.dcim.devices.get(name=args.dev_name).id # Add V4 interfaces to netbox print(f"Adding Interfaces to Device {args.dev_name}") for interface, values in v4_ints.items(): try: nb.dcim.interfaces.create(device=dev_id, name=interface, form_factor=values[1], enabled="true") except pynetbox.RequestError as err: print("NOTE PyNetBox Error is ", err.error) # Get interface IDs and append to v4 dict for interface, values in v4_ints.items(): interface_id = nb.dcim.interfaces.get(name=interface, device=args.dev_name).id v4_ints[interface].append(interface_id) # Get interface IDs and append to v6 dict for interface, values in v6_ints.items(): interface_id = nb.dcim.interfaces.get(name=interface, device=args.dev_name).id v6_ints[interface].append(interface_id) ##add IPv4 to netbox print(f"Adding IPv4 addresses to Device {args.dev_name}") for interface, values in v4_ints.items(): # check if IP already exists v4_check = nb.ipam.ip_addresses.filter(values[0]) if len(v4_check) == 0: print(f"IP {values[0]} not found, adding to {args.dev_name}") try: nb.ipam.ip_addresses.create(address=values[0], interface=values[2]) except pynetbox.RequestError as err: print("NOTE PyNetBox Error is ", err.error) else: print(f"IP {values[0]} already exists, not adding.") v4_ips_to_check.append(values[0]) # Check if IP is not assigned to an interface, add to list if found print("Checking for unassigned IPv4 addresses") for line in v4_ips_to_check: print(f"Checking {line}") ip = nb.ipam.ip_addresses.get(q=line) if ip.interface == None: v4_ips_to_update.append(line) # Search v4_ints dict for IPs found above and copy values to new dict if len(v4_ips_to_update) != 0: print("updating unassigned ips...") for interface, values in v4_ints.items(): for line in v4_ips_to_update: if line == values[0]: v4_ip_update.update( {interface: [values[0], values[1], values[2]]}) # Update IP with interface ID for interfaces, values in v4_ip_update.items(): try: ip = nb.ipam.ip_addresses.get(q=values[0]) print( f"Found existing IP {values[0]} without Interface... Updating" ) ip.update({"interface": values[2]}) except pynetbox.RequestError as err: print("NOTE PyNetBox Error is ", err.error) else: if len(v4_ips_to_update) == 0: pass # Print add Ipv6 to NetBox print(f"Adding IPv6 addresses to Device {args.dev_name}") for interface, values in v6_ints.items(): # check if IP already exists v6_check = nb.ipam.ip_addresses.filter(values[0]) if len(v6_check) == 0: print(f"IP {values[0]} not found, adding to {args.dev_name}") try: nb.ipam.ip_addresses.create(address=values[0], interface=values[2]) except pynetbox.RequestError as err: print("NOTE PyNetBox Error is ", err.error) else: print(f"IP {values[0]} already exists, not adding.") v6_ips_to_check.append(values[0]) # Check if IP is not assigned to an interface, add to list if found print("Checking for unassigned IPv6 addresses") for line in v6_ips_to_check: print(f"Checking {line}") ip = nb.ipam.ip_addresses.get(q=line) if ip.interface == None: v6_ips_to_update.append(line) # Search v6_ints dict for IPs found above and copy values to new dict if len(v6_ips_to_update) != 0: print("updating unassigned ips...") for interface, values in v6_ints.items(): for line in v6_ips_to_update: if line == values[0]: v6_ip_update.update( {interface: [values[0], values[1], values[2]]}) # Update IP with interface ID for interfaces, values in v6_ip_update.items(): try: ip = nb.ipam.ip_addresses.get(q=values[0]) print( f"Found existing IP {values[0]} without Interface... Updating" ) ip.update({"interface": values[2]}) except pynetbox.RequestError as err: print("NOTE PyNetBox Error is ", err.error) else: if len(v6_ips_to_update) == 0: pass print("Done!")
# exit() # Load list of devices with open('device_list.json') as device_list: all_devices = json.load(device_list) username = raw_input("Enter Username: "******"Enter Password : ") print(username + ' ' + password) for device in all_devices: try: print ('Connecting to : ' + device['ip']) #driver created by NAPALM to determine command structure and expects driver = napalm.get_network_driver(str(device['driver'])) #session opens device with driver(ip/hostname, username, password) with driver(str(device['ip']), username, password) as session: # Gets start, running, and candidate(if applicable) for device deviceConfig = session.get_config() #export each config to a file in a local git path for configType, configText in deviceConfig.iteritems(): #specifies the file path that the running config will be written to if configText: filePath = '/git/config_backup/' + device['site'] + '/' + device['platform'] + '/' + str(device['hostname']) + '/' fileName = str(configType) fileString = filePath + fileName if not os.path.exists(filePath): os.makedirs(filePath) print('Writing ' + str(configType) + 'config to : ' + filePath + fileName)
def create_con(device): device_type = device.pop("device_type") driver = get_network_driver(device_type) new_device = driver(**device) print("Connection created") return new_device
def napalm_conn(device_obj): device_type = device_obj.pop("device_type") driver = get_network_driver(device_type) device_conn = driver(**device_obj) device_conn.open() return device_conn
#!/usr/bin/env python3 ##NAPALM Restoration Config ##Written by Homer Walden import sys import napalm if len(sys.argv) != 6: print("You supplied ", len(sys.argv) - 1, " arguments but 5 are needed") print("getrun.py requires: OS, IP, USER, PW, restore_file_name of device") print( "example: python3 getrun.py eos a.b.c.d username password filename.run" ) sys.exit() os = sys.argv[1] ip = sys.argv[2] user = sys.argv[3] passwd = sys.argv[4] filename = sys.argv[5] from napalm import get_network_driver import pprint as pp driver = get_network_driver(os) device = driver(ip, user, passwd) device.open() device.load_replace_candidate(filename) print(device.compare_config()) device.commit_config() device.close() exit()
from napalm import get_network_driver import copy print("\nThis is the playbook contents -----------------------------------") with open("./playbooks/create_loopback.txt", "r") as file: playbook = file.read() print(playbook) driver = get_network_driver("ios") #Error with IOS 15 - solved with optional arguments src: GitHub support pages device = driver("10.242.1.92", "hannibal", "hannibal", optional_args={"global_delay_factor":2}) print("\nConnecting to device -------------------------------------") device.open() device.load_merge_candidate(config = playbook) print("\nMerging the configuration --------------------------------") print("\nPrinting the new device config 'again' --------------------------") print(device.compare_config()) happy = input('Are You happy with this: [yes]') or yes if happy == 'yes' : device.commit_config() print("\nPushing Config ------------------------------------") else: device.discard_config() print("\nDiscarding Config ------------------------------------") device.close()
def get_required_info( self, default_mgmt_if=PLUGIN_SETTINGS["default_management_interface"], default_mgmt_pfxlen=PLUGIN_SETTINGS[ "default_management_prefix_length"], ): """Gather information from the network device that is needed to onboard the device into the NetBox system. Raises: OnboardException('fail-login'): When unable to login to device OnboardException('fail-execute'): When unable to run commands to collect device information OnboardException('fail-general'): Any other unexpected device comms failure. """ self.check_reachability() mgmt_ipaddr = self.ot.ip_address logging.info("COLLECT: device information %s", mgmt_ipaddr) try: platform_slug = self.get_platform_slug() platform_object = self.get_platform_object_from_netbox( platform_slug=platform_slug) if self.ot.platform != platform_object: self.ot.platform = platform_object self.ot.save() driver_name = platform_object.napalm_driver if not driver_name: raise OnboardException( reason="fail-general", message= f"Onboarding for Platform {platform_slug} not supported, as it has no specified NAPALM driver", ) driver = get_network_driver(driver_name) optional_args = settings.NAPALM_ARGS.copy() optional_args["secret"] = self.secret dev = driver( hostname=mgmt_ipaddr, username=self.username, password=self.password, timeout=self.ot.timeout, optional_args=optional_args, ) dev.open() logging.info("COLLECT: device facts") facts = dev.get_facts() logging.info("COLLECT: device interface IPs") ip_ifs = dev.get_interfaces_ip() except ConnectionException as exc: raise OnboardException(reason="fail-login", message=exc.args[0]) except CommandErrorException as exc: raise OnboardException(reason="fail-execute", message=exc.args[0]) except Exception as exc: raise OnboardException(reason="fail-general", message=str(exc)) # locate the interface assigned with the mgmt_ipaddr value and retain # the interface name and IP prefix-length so that we can use it later # when creating the IPAM IP-Address instance. # Note that in some cases (e.g., NAT) the mgmt_ipaddr may differ than # the interface addresses present on the device. We need to handle this. def get_mgmt_info(): """Get the interface name and prefix length for the management interface.""" for if_name, if_data in ip_ifs.items(): for if_addr, if_addr_data in if_data["ipv4"].items(): if if_addr == mgmt_ipaddr: return (if_name, if_addr_data["prefix_length"]) return (default_mgmt_if, default_mgmt_pfxlen) # retain the attributes that will be later used by NetBox processing. self.hostname = facts["hostname"] self.vendor = facts["vendor"].title() self.model = facts["model"].lower() self.serial_number = facts["serial_number"] self.mgmt_ifname, self.mgmt_pflen = get_mgmt_info()
from napalm import get_network_driver driver = get_network_driver('eos') dev = driver(hostname='leaf1a', username='******', password='******') dev.open() dev.load_merge_candidate(filename='napalm_bgp.cfg') diffs = dev.compare_config() if len(diffs) > 0: print(diffs) decision = raw_input("Would you like to commit this change? Y/N\n") if decision == "Y": dev.commit_config() else: print "Goodbye!" else: print('No changes needed') dev.discard_config() dev.close()
from __future__ import print_function import napalm from napalm import get_network_driver import sys import os import json import pprint driver = napalm.get_network_driver("iosxr") device = driver( hostname="10.10.20.70", username="******", password="******", optional_args={"port": 2221}, ) print("Opening ...") device.open() pprint.pprint( device.cli(['show interface description', 'show ip interface brief'])) # cmds = ['show ip interface brief'] # input = device.cli(cmds) # for i in input.keys(): # input[i] = input[i].split('\n') # print(json.dumps(input, sort_keys=True, indent=4))
#!/usr/bin/python import json from napalm import get_network_driver from getpass import getpass from datetime import datetime print "Connecting to Juniper devices" jnpr_device = raw_input("Enter the Juniper Device IP Address:") username = raw_input("Username:"******"Password:"******"junos") vsrx_in_snt = junos_driver(hostname=jnpr_device, username=username, password=password) vsrx_in_snt.open() junos_bgp_neighbors = vsrx_in_snt.get_bgp_neighbors() print(vsrx_in_snt.get_bgp_neighbors()) #print(json.dumps(junos_bgp_neighbors,indent=4) #vsrx_in_snt.close()
conf_file = sys.argv[2] # load device parameter database try: with open("devices.json", "r") as f: device_data = json.load(f) except (ValueError, IOError, OSError) as err: merge_device("Could not read the 'devices' file:", err) # Making a list of routers/keys from convert json. router_list = [router for router in device_data] device_list = [] for router in router_list: driver = get_network_driver(device_data[router]['type']) device = driver(hostname=device_data[router]['IP'], password=device_data[router]['password'], username=device_data[router]['user']) device.open() device.load_merge_candidate(filename='prefix_list.cfg') diffs = device.compare_config() print '=' * 10, '{}'.format(router), '=' * 10 if diffs == "": print("Configuration already applied") device.discard_config() device.close() else: print(diffs) device_list.append([device, router])
def napalm(self, request, pk): """ Execute a NAPALM method on a Device """ device = get_object_or_404(Device, pk=pk) if not device.primary_ip: raise ServiceUnavailable( "This device does not have a primary IP address configured.") if device.platform is None: raise ServiceUnavailable( "No platform is configured for this device.") if not device.platform.napalm_driver: raise ServiceUnavailable( "No NAPALM driver is configured for this device's platform ()." .format(device.platform)) # Check that NAPALM is installed try: import napalm from napalm.base.exceptions import ModuleImportError except ImportError: raise ServiceUnavailable( "NAPALM is not installed. Please see the documentation for instructions." ) # Validate the configured driver try: driver = napalm.get_network_driver(device.platform.napalm_driver) except ModuleImportError: raise ServiceUnavailable( "NAPALM driver for platform {} not found: {}.".format( device.platform, device.platform.napalm_driver)) # Verify user permission if not request.user.has_perm('dcim.napalm_read'): return HttpResponseForbidden() # Connect to the device napalm_methods = request.GET.getlist('method') response = OrderedDict([(m, None) for m in napalm_methods]) ip_address = str(device.primary_ip.address.ip) username = settings.NAPALM_USERNAME password = settings.NAPALM_PASSWORD optional_args = settings.NAPALM_ARGS.copy() if device.platform.napalm_args is not None: optional_args.update(device.platform.napalm_args) # Update NAPALM parameters according to the request headers for header in request.headers: if header[:9].lower() != 'x-napalm-': continue key = header[9:] if key.lower() == 'username': username = request.headers[header] elif key.lower() == 'password': password = request.headers[header] elif key: optional_args[key.lower()] = request.headers[header] d = driver(hostname=ip_address, username=username, password=password, timeout=settings.NAPALM_TIMEOUT, optional_args=optional_args) try: d.open() except Exception as e: raise ServiceUnavailable( "Error connecting to the device at {}: {}".format( ip_address, e)) # Validate and execute each specified NAPALM method for method in napalm_methods: if not hasattr(driver, method): response[method] = {'error': 'Unknown NAPALM method'} continue if not method.startswith('get_'): response[method] = { 'error': 'Only get_* NAPALM methods are supported' } continue try: response[method] = getattr(d, method)() except NotImplementedError: response[method] = { 'error': 'Method {} not implemented for NAPALM driver {}'.format( method, driver) } except Exception as e: response[method] = { 'error': 'Method {} failed: {}'.format(method, e) } d.close() return Response(response)
def main(): module = AnsibleModule( argument_spec=dict( hostname=dict(type='str', required=True), username=dict(type='str', required=True), password=dict(type='str', required=True, no_log=True), dev_os=dict(type='str', required=True, choices=['eos', 'junos', 'iosxr', 'fortios', 'ibm', 'ios', 'nxos']), timeout=dict(type='int', required=False, default=60), optional_args=dict(type='dict', required=False, default=None), filter=dict(type='str', required=False, default='facts'), ), supports_check_mode=True ) if not napalm_found: module.fail_json(msg="the python module napalm is required") hostname = module.params['hostname'] username = module.params['username'] dev_os = module.params['dev_os'] password = module.params['password'] timeout = module.params['timeout'] filter_list = module.params['filter'].split(',') if module.params['optional_args'] is None: optional_args = {} else: optional_args = module.params['optional_args'] # open device connection try: network_driver = get_network_driver(dev_os) device = network_driver(hostname=hostname, username=username, password=password, timeout=timeout, optional_args=optional_args) device.open() except: module.fail_json(msg="cannot connect to device") # retreive data from device facts = {} try: for filter in filter_list: if filter == 'facts': result = device.get_facts() facts['facts'] = result elif filter == 'interfaces': result = device.get_interfaces() facts['interfaces'] = result elif filter == 'interfaces_counter': result = device.get_interfaces_counter() facts['interfaces_counter'] = result elif filter == 'bgp_config': result = device.get_bgp_config() facts['bgp_config'] = result elif filter == 'bgp_neighbors': result = device.get_bgp_neighbors() facts['bgp_neighbors'] = result elif filter == 'bgp_neighbors_detail': result = device.get_bgp_neighbors_detail() facts['bgp_neighbors_detail'] = result elif filter == 'environment': result = device.get_environment() facts['environment'] = result elif filter == 'lldp_neighbors': result = device.get_lldp_neighbors() facts['lldp_neighbors'] = result elif filter == 'lldp_neighbors_detail': result = device.get_lldp_neighbors_detail() facts['lldp_neighbors_detail'] = result else: module.fail_json(msg="filter not recognized: " + filter) except: module.fail_json(msg="cannot retrieve device data") # close device connection try: device.close() except: module.fail_json(msg="cannot close device connection") module.exit_json(ansible_facts=facts)
def main(): module = AnsibleModule( argument_spec=dict( hostname=dict(type='str', required=True), username=dict(type='str', required=True), password=dict(type='str', required=True), timeout=dict(type='int', required=False, default=60), optional_args=dict(required=False, type='dict', default=None), config_file=dict(type='str', required=True), dev_os=dict(type='str', required=True, choices=['eos', 'junos', 'iosxr', 'fortios', 'ibm', 'ios', 'nxos']), commit_changes=dict(type='bool', required=True, choices=BOOLEANS), replace_config=dict(type='bool', required=False, choices=BOOLEANS, default=False), diff_file=dict(type='str', required=False, default=None), get_diffs=dict(type='bool', required=False, choices=BOOLEANS, default=True) ), supports_check_mode=True ) if not napalm_found: module.fail_json(msg="the python module napalm is required") hostname = module.params['hostname'] username = module.params['username'] dev_os = module.params['dev_os'] password = module.params['password'] timeout = module.params['timeout'] config_file = module.params['config_file'] commit_changes = module.params['commit_changes'] replace_config = module.params['replace_config'] diff_file = module.params['diff_file'] get_diffs = module.params['get_diffs'] if module.params['optional_args'] is None: optional_args = {} else: optional_args = module.params['optional_args'] try: network_driver = get_network_driver(dev_os) device = network_driver(hostname=hostname, username=username, password=password, timeout=timeout, optional_args=optional_args) device.open() except: module.fail_json(msg="cannot connect to device") try: if replace_config: device.load_replace_candidate(filename=config_file) else: device.load_merge_candidate(filename=config_file) except: module.fail_json(msg="cannot load config") try: if get_diffs: diff = device.compare_config().encode('utf-8') changed = len(diff) > 0 else: changed = True diff = None if diff_file is not None and get_diffs: save_to_file(diff, diff_file) except: module.fail_json(msg="cannot diff config") try: if module.check_mode or not commit_changes: device.discard_config() else: if changed: device.commit_config() except: module.fail_json(msg="cannot install config") try: device.close() except: module.fail_json(msg="cannot close device connection") module.exit_json(changed=changed, msg=diff)
def main(): requests.packages.urllib3.disable_warnings(InsecureRequestWarning) password = getpass() cisco_rtr1 = { 'hostname' : '184.105.247.70', 'device_type' : 'ios', 'password' : password, 'username' : 'pyclass', 'optional_args' : {} } cisco_rtr2 = { 'hostname' : '184.105.247.71', 'device_type' : 'ios', 'password' : password, 'username' : 'pyclass', 'optional_args' : {} } arista_sw1 = { 'hostname' : '184.105.247.72', 'device_type' : 'eos', 'password' : password, 'username' : 'pyclass', 'optional_args' : {} } arista_sw2 = { 'hostname' : '184.105.247.73', 'device_type' : 'eos', 'password' : password, 'username' : 'pyclass', 'optional_args' : {} } jnpr_srx1 = { 'hostname' : '184.105.247.76', 'device_type' : 'junos', 'password' : password, 'username' : 'pyclass', 'optional_args' : {} } cisco_nxos = { 'hostname' : 'nxos1.twb-tech.com', 'device_type' : 'nxos', 'password' : password, 'username' : 'pyclass', 'optional_args' : {'port' : '8443', 'nxos_protocol' : 'https' } } # devices = (cisco_rtr1, cisco_rtr2, arista_sw1, arista_sw2, jnpr_srx1, cisco_nxos) # devices = (cisco_rtr1, cisco_rtr2) devices = (cisco_rtr1, cisco_rtr2, arista_sw1, arista_sw2, cisco_nxos) napalm_conns = [] template_vars = { 'dns1': '1.1.1.1', 'dns2': '8.8.8.8', } base_path = '/home/tarmstrong/projects/pynetauto/7class' for a_device in devices: # print("\n") # pprint(a_device) print("\n") device_type = a_device.pop('device_type') driver = get_network_driver(device_type) device = driver(**a_device) napalm_conns.append(device) print(" ******************** DEVICE START **********************") print("\nDevice created! Host: {}".format(a_device['hostname'])) device.open() print("\nDevice connection opened! Type: {}".format(device_type)) device.load_template("dns", template_path=base_path, **template_vars) print(device.compare_config()) device.commit_config() ping_google(device) print("\n\n")
def napalm(self, request, pk): """ Execute a NAPALM method on a Device """ device = get_object_or_404(Device, pk=pk) if not device.primary_ip: raise ServiceUnavailable("This device does not have a primary IP address configured.") if device.platform is None: raise ServiceUnavailable("No platform is configured for this device.") if not device.platform.napalm_driver: raise ServiceUnavailable("No NAPALM driver is configured for this device's platform ().".format( device.platform )) # Check that NAPALM is installed try: import napalm from napalm.base.exceptions import ModuleImportError except ImportError: raise ServiceUnavailable("NAPALM is not installed. Please see the documentation for instructions.") # Validate the configured driver try: driver = napalm.get_network_driver(device.platform.napalm_driver) except ModuleImportError: raise ServiceUnavailable("NAPALM driver for platform {} not found: {}.".format( device.platform, device.platform.napalm_driver )) # Verify user permission if not request.user.has_perm('dcim.napalm_read'): return HttpResponseForbidden() # Connect to the device napalm_methods = request.GET.getlist('method') response = OrderedDict([(m, None) for m in napalm_methods]) ip_address = str(device.primary_ip.address.ip) optional_args = settings.NAPALM_ARGS.copy() if device.platform.napalm_args is not None: optional_args.update(device.platform.napalm_args) d = driver( hostname=ip_address, username=settings.NAPALM_USERNAME, password=settings.NAPALM_PASSWORD, timeout=settings.NAPALM_TIMEOUT, optional_args=optional_args ) try: d.open() except Exception as e: raise ServiceUnavailable("Error connecting to the device at {}: {}".format(ip_address, e)) # Validate and execute each specified NAPALM method for method in napalm_methods: if not hasattr(driver, method): response[method] = {'error': 'Unknown NAPALM method'} continue if not method.startswith('get_'): response[method] = {'error': 'Only get_* NAPALM methods are supported'} continue try: response[method] = getattr(d, method)() except NotImplementedError: response[method] = {'error': 'Method {} not implemented for NAPALM driver {}'.format(method, driver)} except Exception as e: response[method] = {'error': 'Method {} failed: {}'.format(method, e)} d.close() return Response(response)
username="******", password=password, optional_args={"port": 8443}, ) eos1 = dict( hostname="arista1.lasthop.io", device_type="eos", username="******", password=password, ) # Device we are testing my_device = cisco3 # NAPALM Class Selection/Object Creation device_type = my_device.pop("device_type") driver = get_network_driver(device_type) device = driver(**my_device) # NAPALM Action print() print("\n\n>>>Test device open") device.open() print() # output = device.get_facts() output = device.get_interfaces() # output = device.get_lldp_neighbors() pprint(output) print()
def dev_base_connection(self, base_address, devtype, base_username, base_password, time_out): driver = get_network_driver(devtype) device = driver(base_address, base_username, base_password, time_out) return device
import napalm import os import jinja2 config_dir = os.path.join(os.path.dirname(__file__), 'conf') jinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader(config_dir), autoescape=True) from pprint import pprint driver = napalm.get_network_driver('junos') device = driver(hostname='172.16.209.101', username='******', password='******', optional_args={'port': 830}) #device.close() device.open() print(device.username) if device.is_alive(): #pprint(device.get_facts()) Lst_interface = device.get_interfaces() print(Lst_interface) #for pprint(Lst_interface.get('ge-0/0/0')) mapping_interfaces = { 'em2': 'ge-0/0/0',
#!/usr/bin/python3 from napalm import get_network_driver device1 = get_network_driver('ios') #connecting to device device = device1('192.168.234.131', 'lalit', 'cisco') print([i for i in dir(device) if 'load' in i]) #open session with device device.open() #merging configuration print(device.load_merge_candidate(filename='myrouter.txt')) #check the difference print(device.compare_config()) #now commit the config applid by file on router c = input("confirm with y|n to apply configuration : ") if c == 'y' or c == 'Y': print("commiting the configuration") device.commit_config() res = input("Do you want to rollback changes : y|n") if res == 'y' or res == 'Y': device.rollback() else: print("no rollbacks applied") elif c == 'n' or c == 'N': print("discarding configuration ") device.discard_config() else: print("please type only y|Y or n|N")
#!/usr/bin/env python3 # config_2_json.py # Micah Raabe # Lab - NAPALM Changes, Validation, and Rollback from napalm import get_network_driver import json driver = get_network_driver('eos') device = driver('172.16.2.10', 'admin', 'alta3') device.open() # start the connection config = device.get_config() print("UGLY JASON-LIKE BLOB:\r" ) print(device.get_config()) print("REAL JASON:\r" ) print(json.dumps( config ,indent=4, separators=(',', ': ')))