Connect to a device with Napalm

NAPALM (Network Automation and Programmability Abstraction Layer with Multivendor support) is a Python library that implements a set of functions to interact with different network device Operating Systems using a unified API. Useful library to connect to devices without worrying about their type.

import napalm
import json

cisco_sandbox_devices = {
    "hostname": "sandbox-iosxe-recomm-1.cisco.com",
    "port": 22,
    "username": "developer",
    "password": "C1sco12345",
    "device_type": "cisco_ios",
}

IOS = "ios"
NXOS = "nxos"
NXOS_SSH = "nxos_ssh"

devices = cisco_sandbox_devices

for device_type, device in devices.items():

    print(f"\n----- connecting to device {device_type}: {device['hostname']} ----------")
    driver = napalm.get_network_driver(device_type)
    if device_type == IOS:
        napalm_device = driver(
            hostname=device["hostname"],
            username=device["username"],
            password=device["password"],
        )
    else:
        napalm_device = driver(
            hostname=device["hostname"],
            username=device["username"],
            password=device["password"],
            optional_args={"port": device["port"]},
        )

    napalm_device.open()

    print("\n----- facts ----------")
    print(json.dumps(napalm_device.get_facts(), sort_keys=True, indent=4))

    print("\n----- interfaces ----------")
    print(json.dumps(napalm_device.get_interfaces(), sort_keys=True, indent=4))

    print("\n----- vlans ----------")
    try:
        print(json.dumps(napalm_device.get_vlans(), sort_keys=True, indent=4))
    except NotImplementedError as e:
        print(f"oops, looks like this isn't implemented for {device['hostname']}, error: {e}")

    print("\n----- snmp ----------")
    print(json.dumps(napalm_device.get_snmp_information(), sort_keys=True, indent=4))

    print("\n----- interface counters ----------")
    try:
        print(json.dumps(napalm_device.get_interfaces_counters(), sort_keys=True, indent=4))
    except NotImplementedError as e:
        print(f"oops, looks like this isn't implemented for {device['hostname']}, error: {e}")

    print("\n----- environment ----------")
    try:
        print(json.dumps(napalm_device.get_environment(), sort_keys=True, indent=4))
    except (KeyError, IOError, napalm.pyIOSXR.exceptions.XMLCLIError) as e:
        print(f"oops, looks like there is a NAPALM exception for {device['hostname']}, error: {e}")

    napalm_device.close()