### Device Configuration Example Source: https://github.com/napalm-automation/napalm/blob/develop/test/ios/ios/mock_data/show_run_interface_GigabitEthernet2.txt Example of a device's current configuration, showing interface details and IP addressing. ```text ! interface GigabitEthernet2 ip address 192.168.0.1 255.255.255.0 negotiation auto end ``` -------------------------------- ### Install Dependencies with uv Source: https://github.com/napalm-automation/napalm/blob/develop/CONTRIBUTING.md Install all project dependencies using uv. This command synchronizes all defined groups. ```bash uv sync --all-groups ``` -------------------------------- ### Example Device Configuration Source: https://github.com/napalm-automation/napalm/blob/develop/test/ios/ios/mock_data/show_run_interface_GigabitEthernet1.txt This is an example of a network device configuration snippet, showing interface settings and IP addressing. ```text !\ninterface GigabitEthernet1\n ip address dhcp\n negotiation auto\n no mop enabled\nend ``` -------------------------------- ### Install Documentation Dependencies Source: https://github.com/napalm-automation/napalm/blob/develop/docs/contributing/index.rst Install the necessary dependencies for building the documentation using pip. This should be done within a Python virtual environment. ```console pip install -r docs/requirements.txt ``` -------------------------------- ### Install NAPALM Dependencies on Ubuntu/Debian Source: https://github.com/napalm-automation/napalm/blob/develop/docs/installation/ios.rst Installs necessary development libraries for NAPALM on Ubuntu and Debian systems using apt-get. ```bash sudo apt-get install -y --force-yes libssl-dev libffi-dev python-dev python-cffi ``` -------------------------------- ### Start Vagrant Environment Source: https://github.com/napalm-automation/napalm/blob/develop/docs/tutorials/lab.rst Initiates the virtual environment defined in the Vagrantfile. This command will create and start the specified virtual machines, including the Arista vEOS box. ```bash $ vagrant up --provider virtualbox ... [output omitted] ... ``` -------------------------------- ### Install NAPALM on FreeBSD using pkg Source: https://github.com/napalm-automation/napalm/blob/develop/docs/installation/index.rst Install NAPALM and all drivers for the default Python version on FreeBSD. For specific Python versions, use the pyXY-napalm package. ```bash pkg install net-mgmt/py-napalm ``` ```bash pkg install pyXY-napalm ``` -------------------------------- ### Building Configuration Source: https://github.com/napalm-automation/napalm/blob/develop/test/ios/ios/mock_data/show_run_interface_GigabitEthernet3.txt This example shows the current configuration of a network device. It is typically used to verify changes or understand the device's state before and after applying new configurations. ```text !interface GigabitEthernet3 no ip address shutdown negotiation auto end ``` -------------------------------- ### Install NAPALM using pip Source: https://github.com/napalm-automation/napalm/blob/develop/docs/installation/index.rst Use this command to install NAPALM and all available core drivers. Ensure you are using Python 3.7+ for versions 4.0.0 and later, or Python 3.6+ for versions 3.0.0 and later. ```bash pip install napalm ``` -------------------------------- ### Call Mocked Function (get_interfaces) Source: https://github.com/napalm-automation/napalm/blob/develop/docs/tutorials/mock_driver.rst Example of calling a mocked function after the device has been opened. This specific call requires a corresponding mocked data file for 'get_interfaces'. ```python >>> device.open() NotImplementedError: You can provide mocked data in get_interfaces.1 ``` ```python >>> device.get_network_instances() ``` -------------------------------- ### Instantiate and Use Custom NAPALM Driver Source: https://github.com/napalm-automation/napalm/blob/develop/docs/tutorials/extend_driver.rst This example demonstrates how to instantiate a NAPALM driver, open a device connection, and call a custom method like 'get_my_banner'. Ensure you have the necessary credentials and network connectivity. ```python >>> import napalm >>> ios_device='10.1.100.49' >>> ios_user='ntc' >>> ios_password='ntc123' >>> driver = napalm.get_network_driver('ios') >>> device = driver(ios_device, ios_user, ios_password) >>> device.open() >>> device.get_my_banner() {'device': u'NYC-SW01', 'room': u'1004', 'site': u'NYC', 'floor': u'10'} ``` -------------------------------- ### Install NAPALM Dependencies on RedHat/CentOS Source: https://github.com/napalm-automation/napalm/blob/develop/docs/installation/ios.rst Installs necessary development tools and libraries for NAPALM on RedHat and CentOS systems using yum. ```bash sudo yum install -y python-pip gcc openssl openssl-devel libffi-devel python-devel ``` -------------------------------- ### Install NAPALM Junos Dependencies on RedHat/CentOS Source: https://github.com/napalm-automation/napalm/blob/develop/docs/installation/junos.rst Installs Python, development tools, and SSL/TLS libraries needed for NAPALM Junos on RedHat and CentOS systems. ```bash sudo yum install -y python-pip python-devel libxml2-devel libxslt-devel gcc openssl openssl-devel libffi-devel ``` -------------------------------- ### Install NAPALM Junos Dependencies on Ubuntu/Debian Source: https://github.com/napalm-automation/napalm/blob/develop/docs/installation/junos.rst Installs required development libraries and Python headers for NAPALM Junos on Ubuntu and Debian systems. ```bash sudo apt-get install -y --force-yes libxslt1-dev libssl-dev libffi-dev python-dev python-cffi ``` -------------------------------- ### Run Documentation Doctests Source: https://github.com/napalm-automation/napalm/blob/develop/CONTRIBUTING.md Execute documentation doctests after the standard test suite has passed. This ensures documentation examples are accurate. ```bash uv run make doctest ``` -------------------------------- ### Handle Missing Test Cases in NAPALM Source: https://github.com/napalm-automation/napalm/blob/develop/docs/development/testing_framework.rst This example demonstrates how the testing framework handles missing test cases, resulting in a FAILED status. Ensure test case directories exist. ```bash py.test test/unit/test_getters.py::TestGetter::test_get_bgp_neighbors ``` -------------------------------- ### Configure Device with NAPALM CLI Source: https://github.com/napalm-automation/napalm/blob/develop/docs/cli.rst Configure a network device using NAPALM CLI with merge strategy and dry-run enabled. This example shows a configuration diff. ```bash napalm --user vagrant --password vagrant --vendor eos --optional_args "port=12443" localhost configure new_config.txt --strategy merge --dry-run ``` ```diff @@ -8,7 +8,7 @@ ! transceiver qsfp default-mode 4x10G ! - hostname myhost + hostname a-new-hostname ! spanning-tree mode mstp ! @@ -20,6 +20,7 @@ username vagrant privilege 15 role network-admin secret 5 $1$gxUZF/4Q$FoUvji7hq0HpJGxc67PJM0 ! interface Ethernet1 + description "TBD" ! interface Ethernet2 ! ``` -------------------------------- ### Install Configuration on Device with NAPALM Ansible Source: https://github.com/napalm-automation/napalm/blob/develop/docs/tutorials/ansible-napalm.rst Use the napalm_install_config module to push configuration to a network device. Supports committing changes, replacing the entire configuration, and generating diffs. ```yaml - assemble: src=../compiled/{{ inventory_hostname }}/ dest=../compiled/{{ inventory_hostname }}/running.conf - napalm_install_config: hostname={{ inventory_hostname }} username={{ user }} dev_os={{ os }} password={{ passwd }} config_file=../compiled/{{ inventory_hostname }}/running.conf commit_changes={{ commit_changes }} replace_config={{ replace_config }} get_diffs=True diff_file=../compiled/{{ inventory_hostname }}/diff ``` -------------------------------- ### Install NAPALM Ansible Modules Source: https://github.com/napalm-automation/napalm/blob/develop/docs/tutorials/ansible-napalm.rst Clone the napalm-ansible repository into your Ansible module path. Ensure your ansible.cfg is configured to point to the correct library directory. ```bash cd ~/workspace git clone https://github.com/napalm-automation/napalm-ansible.git ``` -------------------------------- ### Create Custom Method for Banner Parsing Source: https://github.com/napalm-automation/napalm/blob/develop/docs/tutorials/extend_driver.rst Implement a custom method to parse specific command output, such as 'show banner motd'. This example parses the banner to extract site, device, floor, and room information. It uses the internal _send_command method to retrieve output. ```python from napalm.ios.ios import IOSDriver class CustomIOSDriver(IOSDriver): """Custom NAPALM Cisco IOS Handler.""" def get_my_banner(self): command = 'show banner motd' output = self._send_command(command) return_vars = {} for line in output.splitlines(): split_line = line.split() if "Site:" == split_line[0]: return_vars["site"] = split_line[1] elif "Device:" == split_line[0]: return_vars["device"] = split_line[1] elif "Floor:" == split_line[0]: return_vars["floor"] = split_line[1] elif "Room:" == split_line[0]: return_vars["room"] = split_line[1] return return_vars ``` -------------------------------- ### Run NAPALM Tests Locally with act Source: https://github.com/napalm-automation/napalm/blob/develop/docs/development/testing_framework.rst Use nektos/act and Docker to run the standard tests locally before opening a pull request. Ensure Docker is installed and running. ```console $ act -j std_tests [build/std_tests-4] 🚀 Start image=catthehacker/ubuntu:act-latest [build/std_tests-3] 🚀 Start image=catthehacker/ubuntu:act-latest [build/std_tests-1] 🚀 Start image=catthehacker/ubuntu:act-latest [build/std_tests-2] 🚀 Start image=catthehacker/ubuntu:act-latest [build/std_tests-5] 🚀 Start image=catthehacker/ubuntu:act-latest [build/std_tests-4] 🐳 docker pull image=catthehacker/ubuntu:act-latest platform= username= forcePull=true [build/std_tests-1] 🐳 docker pull image=catthehacker/ubuntu:act-latest platform= username= forcePull=true [build/std_tests-3] 🐳 docker pull image=catthehacker/ubuntu:act-latest platform= username= forcePull=true [build/std_tests-5] 🐳 docker pull image=catthehacker/ubuntu:act-latest platform= username= forcePull=true [build/std_tests-2] 🐳 docker pull image=catthehacker/ubuntu:act-latest platform= username= forcePull=true ... | --------------------------------------------------------------------- | TOTAL 9258 1836 80% | | ================= 619 passed, 80 skipped, 3 warnings in 19.97s ================= [build/std_tests-5] ✅ Success - Main Run Tests [build/std_tests-5] ⭐ Run Post Setup Python 3.11 [build/std_tests-5] 🐳 docker exec cmd=[node /var/run/act/actions/actions-setup-python@v2/dist/cache-save/index.js] user= workdir= [build/std_tests-5] ✅ Success - Post Setup Python 3.11 [build/std_tests-5] 🏁 Job succeeded ``` -------------------------------- ### Get NXOS Checkpoint File Source: https://github.com/napalm-automation/napalm/blob/develop/docs/support/nxos.rst Obtain a checkpoint file representing the device's current configuration. Ensure the device is running NXOS 6.1 and has 'nxapi' and 'scp-server' features enabled. ```python device.open() checkpoint = device._get_checkpoint_file() print(checkpoint) device.close() ``` -------------------------------- ### YAML Validator File Example Source: https://github.com/napalm-automation/napalm/blob/develop/docs/validate/index.rst This YAML structure defines the expected state for various NAPALM getters. Use '_mode: strict' for exact matches and '_kwargs' to pass arguments to specific getters. ```yaml --- - get_facts: os_version: 7.0(3)I2(2d) interface_list: _mode: strict list: - Vlan5 - Vlan100 hostname: n9k2 - get_environment: memory: used_ram: '<15.0' available_ram: '10.0<->20.0' cpu: 0/RP0/CPU0 '%usage': '<15.0' - get_bgp_neighbors: global: router_id: 192.0.2.2 peers: _mode: strict 192.0.2.2: is_enabled: true address_family: ipv4: sent_prefixes: 5 received_prefixes: '<10' ipv6: sent_prefixes: 2 received_prefixes: '<5' - get_interfaces_ip: Ethernet2/1: ipv4: 192.0.2.1: prefix_length: 30 - ping: _name: ping_google _kwargs: destination: 8.8.8.8 source: 192.168.1.1 success: packet_loss: 0 _mode: strict - ping: _name: something_else _kwargs: destination: 10.8.2.8 source: 192.168.1.1 success: packet_loss: 0 _mode: strict ``` -------------------------------- ### NAPALM Test Failure Example Source: https://github.com/napalm-automation/napalm/blob/develop/docs/development/testing_framework.rst Illustrates a test failure scenario within the NAPALM framework, specifically when a test case is not found. This often indicates an issue with the mocked data setup. ```python cls = , test_case = 'no_test_case_found' @functools.wraps(func) def wrapper(cls, test_case): cls.device.device.current_test = func.__name__ cls.device.device.current_test_case = test_case try: # This is an ugly, ugly, ugly hack because some python objects don't load # as expected. For example, dicts where integers are strings result = json.loads(json.dumps(func(cls))) except IOError: if test_case == "no_test_case_found": > pytest.fail("No test case for '{}' found".format(func.__name__)) E Failed: No test case for 'test_get_bgp_neighbors' found ../napalm/napalm.base/test/getters.py:64: Failed ``` -------------------------------- ### Get NAPALM Mock Driver Source: https://github.com/napalm-automation/napalm/blob/develop/docs/tutorials/mock_driver.rst Import and get the mock network driver from NAPALM. This driver is used for testing purposes. ```python >>> import napalm >>> driver = napalm.get_network_driver('mock') ``` -------------------------------- ### Build Documentation Locally Source: https://github.com/napalm-automation/napalm/blob/develop/docs/contributing/index.rst Build the documentation locally after making changes. Navigate to the 'docs' directory before running this command. ```console # in the docs directory make html ``` -------------------------------- ### Compare NXOS Configuration Merge Source: https://github.com/napalm-automation/napalm/blob/develop/docs/support/nxos.rst Load a configuration into the merge candidate and then print the differences between the candidate and running configurations. This method is not atomic. ```python candidate_cfg = """ interface loopback0 ip address 10.1.4.5/32 ip router ospf 100 area 0.0.0.1 """ nxos1.load_merge_candidate(config=candidate_cfg) print(nxos1.compare_config()) ``` -------------------------------- ### Replace Device Configuration from File Source: https://github.com/napalm-automation/napalm/blob/develop/docs/tutorials/changing_the_config.rst Loads a candidate configuration from a file to replace the entire current configuration. Use `compare_config()` to review changes before committing. ```python device.load_replace_candidate(filename='test/unit/eos/new_good.conf') ``` -------------------------------- ### Get Device Configuration Source: https://github.com/napalm-automation/napalm/blob/develop/test/ios/ios/mock_data/show_run_interface_GigabitEthernet2.txt Retrieves the current configuration of a network device. This is useful for auditing or backup purposes. ```python from napalm import get_network_driver driver = get_network_driver('ios') # Replace with your device's IP address, username, and password optional_args = { 'secret': 'my-enable-password' } # Replace with your device's IP address, username, and password device = driver('192.168.0.1', 'myuser', 'mypassword', optional_args=optional_args) device.open() # Get the configuration config = device.get_config() # Print the configuration print(config['running']) device.close() ``` -------------------------------- ### Python NAPALM Driver Initialization Source: https://github.com/napalm-automation/napalm/blob/develop/docs/validate/index.rst This Python code demonstrates how to import the NAPALM library and initialize network drivers for different vendors (EOS and Junos). Ensure you have the necessary credentials and connection details. ```python from napalm import get_network_driver import pprint eos_driver = get_network_driver("eos") eos_config = { "hostname": "localhost", "username": "vagrant", "password": "vagrant", "optional_args": {"port": 12443}, } junos_driver = get_network_driver("junos") junos_config = { "hostname": "localhost", "username": "vagrant", "password": "", "optional_args": {"port": 12203}, } ``` -------------------------------- ### Download Sample Arista Configuration Files Source: https://github.com/napalm-automation/napalm/blob/develop/docs/tutorials/lab.rst Downloads sample Arista vEOS configuration files from a GitHub repository. These files can be used for testing NAPALM functionalities. ```bash $ for f in new_good.conf merge_good.conf merge_typo.conf; $ do $ wget https://raw.githubusercontent.com/napalm-automation/napalm/master/docs/tutorials/sample_configs/$f $ done ``` -------------------------------- ### Ruff Linting Check Source: https://github.com/napalm-automation/napalm/blob/develop/CONTRIBUTING.md Run Ruff for code linting across the project. This command checks for style guide violations. ```bash uv run --no-project ruff check . ``` -------------------------------- ### Mocked Error Data Source: https://github.com/napalm-automation/napalm/blob/develop/docs/tutorials/mock_driver.rst JSON structure to simulate an exception during a driver call. This example defines data to raise a 'ConnectionClosedException' when 'device.get_interfaces()' is called. ```json { "exception": "ConnectionClosedException", "args": [], "kwargs": {} } ``` -------------------------------- ### Compare Configuration Changes Source: https://github.com/napalm-automation/napalm/blob/develop/docs/tutorials/changing_the_config.rst Displays the differences between the candidate configuration and the running configuration. This is useful for reviewing changes before applying them. ```python print(device.compare_config()) ``` -------------------------------- ### Get Network Driver Source: https://github.com/napalm-automation/napalm/blob/develop/docs/index.rst Use `get_network_driver` to import the appropriate driver for a specific network operating system. This function returns the driver class. ```python >>> from napalm import get_network_driver >>> get_network_driver('eos') ``` ```python >>> get_network_driver('iosxr_netconf') ``` ```python >>> get_network_driver('iosxr') ``` ```python >>> get_network_driver('junos') ``` ```python >>> get_network_driver('nxos') ``` ```python >>> get_network_driver('ios') ``` -------------------------------- ### Using Optional Arguments with NAPALM Driver Source: https://github.com/napalm-automation/napalm/blob/develop/docs/support/index.rst Demonstrates how to pass a dictionary of optional arguments to a NAPALM driver when initializing a device object. This allows for customization of driver behavior. ```python from napalm import get_network_driver driver = get_network_driver('eos') optional_args = {'my_optional_arg1': 'my_value1', 'my_optional_arg2': 'my_value2'} device = driver('192.168.76.10', 'dbarroso', 'this_is_not_a_secure_password', optional_args=optional_args) device.open() ``` -------------------------------- ### Skip NotImplemented Methods in NAPALM Tests Source: https://github.com/napalm-automation/napalm/blob/develop/docs/development/testing_framework.rst NAPALM tests automatically skip methods that are not implemented for a specific driver, as shown by the SKIPPED status in this example. ```bash py.test test/unit/test_getters.py::TestGetter::test_get_probes_config ``` -------------------------------- ### Build Configuration Source: https://github.com/napalm-automation/napalm/blob/develop/test/ios/ios/mock_data/show_run_interface_GigabitEthernet2.txt Builds a configuration on a network device. This is useful for deploying changes or new configurations. ```python from napalm import get_network_driver driver = get_network_driver('ios') # Replace with your device's IP address, username, and password optional_args = { 'secret': 'my-enable-password' } # Replace with your device's IP address, username, and password device = driver('192.168.0.1', 'myuser', 'mypassword', optional_args=optional_args) device.open() # Configuration to load config_to_load = { 'running': 'interface Loopback0\n ip address 1.1.1.1 255.255.255.255\nend' } # Load the configuration device.load_merge_candidate(config=config_to_load['running']) # Commit the configuration # device.commit_config() # Discard the configuration if not committing # device.discard_config() device.close() ``` -------------------------------- ### Merge Configuration from String Source: https://github.com/napalm-automation/napalm/blob/develop/docs/tutorials/changing_the_config.rst Loads a configuration snippet from a string to be merged with the existing running configuration. Use `compare_config()` to review changes before committing. ```python device.load_merge_candidate(config='hostname test\ninterface Ethernet2\ndescription bla') ``` -------------------------------- ### Mocked Data for CLI Command 1 Source: https://github.com/napalm-automation/napalm/blob/develop/docs/tutorials/mock_driver.rst Raw output for the first CLI command 'show interface Ethernet 1/1'. This data is stored in a file named 'cli.1.show_interface_Ethernet_1_1.0'. ```text Ethernet1/1 is up admin state is up, Dedicated Interface ``` -------------------------------- ### Instantiate Mock Driver with Path Source: https://github.com/napalm-automation/napalm/blob/develop/docs/tutorials/mock_driver.rst Instantiate the mock driver, providing a path to the directory containing mock result files. This driver can be used within a 'with' statement for automatic opening and closing. ```python >>> with driver('foo', 'user', 'pass', optional_args={'path': '/tmp/mock'}) as device: ``` -------------------------------- ### Vagrantfile Configuration for Arista vEOS Source: https://github.com/napalm-automation/napalm/blob/develop/docs/tutorials/lab.rst This Vagrantfile defines a virtual environment with a base box and an Arista vEOS box. It is used with the `vagrant up` command to start the virtual machines. ```ruby # -*- mode: ruby -*- # vi: set ft=ruby : $: << File.expand_path("../lib", __FILE__) require 'vagrant' Vagrant.configure("2") do |config| config.vm.define :eos do |eos| eos.vm.box = "vEOS-lab-quickstart" eos.vm.hostname = "eos" eos.vm.network "private_network", ip: "192.168.56.101" eos.vm.provider "virtualbox" do |vb| vb.memory = 1024 end end end ``` -------------------------------- ### Generate Junos Compliance Report (Compliant) Source: https://github.com/napalm-automation/napalm/blob/develop/docs/validate/index.rst Generates a compliance report for a Junos device using the defined validation file. Requires 'junos_driver' and 'junos_config'. This example shows a fully compliant device. ```python with junos_driver(**junos_config) as junos: pprint.pprint(junos.compliance_report("validate-junos.yml")) ``` -------------------------------- ### Mocked Data for CLI Command 2 Source: https://github.com/napalm-automation/napalm/blob/develop/docs/tutorials/mock_driver.rst Raw output for the second CLI command 'show interface Ethernet 1/2'. This data is stored in a file named 'cli.1.show_interface_Ethernet_1_2.1'. ```text Ethernet1/2 is up admin state is up, Dedicated Interface ``` -------------------------------- ### Using NAPALM Context Manager Source: https://github.com/napalm-automation/napalm/blob/develop/docs/tutorials/context_manager.rst Use the context manager to automatically open and close device sessions. This is the recommended approach for most situations. Ensure the NAPALM driver is imported and instantiated. ```python from napalm import get_network_driver driver = get_network_driver('eos') with driver('localhost', 'vagrant', 'vagrant', optional_args={'port': 12443}) as device: print(device.get_facts()) print(device.get_interfaces_counters()) ``` -------------------------------- ### Handle Self-Signed Certificate Tab Character Source: https://github.com/napalm-automation/napalm/blob/develop/docs/support/ios.rst Cisco IOS adds a tab character to the quit line of self-signed certificates. This example shows how to inspect the line and demonstrates the tab character's ASCII value. ```python >>> for char in line: ... print("{}: {}".format(repr(char), ord(char))) ... ' ': 32 # space ' ': 32 # space '\t': 9 # tab 'q': 113 'u': 117 'i': 105 't': 116 '\n': 10 ``` -------------------------------- ### Connect to a Network Device using NAPALM Source: https://github.com/napalm-automation/napalm/blob/develop/docs/tutorials/changing_the_config.rst Establishes a connection to a network device using the specified driver. Ensure you have the correct device IP, username, and password. ```python from napalm import get_network_driver driver = get_network_driver('eos') device = driver('192.168.76.10', 'dbarroso', 'this_is_not_a_secure_password') device.open() ``` -------------------------------- ### Verify Configuration Rollback Source: https://github.com/napalm-automation/napalm/blob/develop/docs/tutorials/changing_the_config.rst Retrieves the running configuration and checks if specific configuration lines (e.g., 'ntp') are absent, indicating a successful rollback. ```python output = device.get_config()["running"] "ntp" in output ``` -------------------------------- ### NAPALM CLI Help Source: https://github.com/napalm-automation/napalm/blob/develop/docs/cli.rst Display the help message for the NAPALM CLI tool to understand available commands and options. ```bash napalm --help ```