Date created: Sunday, April 30, 2023 4:51:05 PM. Last modified: Sunday, April 30, 2023 4:51:05 PM
napalm_with_ssh_tunnel.py
Use NAPALM via an SSH jumphost:
def get_device(ip_address, hostname, username, password, secret, telnet): """Get interfaces and config.""" ip_address = ''.join(ip_address) ssh_config = '~/.ssh/config' ssh_key = '~/.ssh/priv_key.pem' driver = napalm.get_network_driver('ios') devnull = open(os.devnull, 'w') sys.stderr = devnull ssh_tunnel_active = False if telnet: ssh_tunnel = SSHTunnelForwarder(('IP_OF_JUMPHOST', 22), ssh_username='jump', ssh_pkey=ssh_key, remote_bind_address=(ip_address, 23), local_bind_address=('127.0.0.1', 10023)) ssh_tunnel.start() ssh_tunnel_active = True device = driver(hostname='127.0.0.1', username=username, password=password, optional_args={'dest_file_system': 'blah:', 'transport': 'telnet', 'port': 10023, 'secret': secret}) elif secret: device = driver(hostname=ip_address, username=username, password=password, optional_args={'ssh_config_file': ssh_config, 'dest_file_system': 'blah:', 'secret': secret}) else: device = driver(hostname=ip_address, username=username, password=password, optional_args={'ssh_config_file': ssh_config, 'dest_file_system': 'blah:'}) print('Connecting to ' + hostname + '...') try: device.open() except (EOFError, SSHException, NetMikoTimeoutException, NetMikoAuthenticationException) as err: print('Unable to connect to ' + hostname + ', error was: ' + str(err)) if ssh_tunnel_active: ssh_tunnel.stop() if 'Authentication' in str(err): raise AuthError('Auth failed') from err else: raise ConnectError('Connection failed') from err except (ValueError) as err: print('Unable to connect to ' + hostname + ', error was: ' + str(err)) if ssh_tunnel_active: ssh_tunnel.stop() raise ConnectError('Connection failed') from err print('Connected to ' + hostname) print('Getting interfaces...') interfaces = device.get_interfaces() print('Done') print('Getting config...') config = device.get_config(retrieve=u'running') print('Done') device.close() if ssh_tunnel_active: ssh_tunnel.stop() return(interfaces, config)
Previous page: NETCONF on IOS-XR Setup
Next page: Netlab Notes