netmiko Documentation
repository·develop·Indexed 26 days ago
https://github.com/ktbyers/netmikoA multi-vendor Python library designed to simplify legacy CLI connections to network devices. Netmiko abstracts low-level state control and regex pattern matching to facilitate gathering output from show commands and making configuration changes across a wide range of platforms. It provides tools for SSH/Telnet connections via ConnectHandler, support for terminal server redispatching, and encryption handling for sensitive data in YAML configurations.
What's inside netmiko
- The official Netmiko documentation has moved to GitHub Pages. For general project information and usage instructions, refer to the README. For detailed technical reference and API documentation, use the dedicated documentation site.
Connect using SSH keys or SSH Config files
developNetmiko supports SSH key-based authentication and the use of local SSH configuration files.
- SSH Keys: Set
use_keys=Trueand provide the path to your private key inkey_filewithin the device dictionary. - SSH Config: Provide the path to your SSH config file using the
ssh_config_filekey in the device dictionary.
- SSH Keys: Set
Install Netmiko via pip
developTo install the Netmiko library, use the standard Python package manager, pip.
$ pip install netmikoSet up the Netmiko test environment
developTo run the local test suite, you must first initialize the test configuration files by copying the provided examples in the
netmiko/tests/etcdirectory.cd ./netmiko/tests/etc cp test_devices.yml.example test_devices.yml cp responses.yml.example responses.yml cp commands.yml.example commands.ymlApply configuration changes
developTo apply configuration changes, use
send_config_set(commands)for a list of commands orsend_config_from_file(filename)to read commands from a file. Netmiko automatically handles entering and exiting configuration mode. After applying changes, remember to save the configuration using the platform-appropriate method (e.g.,save_config()for most platforms, orcommit()for Cisco-XR, Juniper-Junos, and Palo Alto).# Applying a list of commands commands = ["logging buffered 100000"] with ConnectHandler(**device) as net_connect: output = net_connect.send_config_set(commands) output += net_connect.save_config() # Applying from a file with ConnectHandler(**device) as net_connect: output = net_connect.send_config_from_file("config_changes.txt") output += net_connect.save_config()Configure test devices and responses
developAfter copying the example files, you must customize them to define your test parameters:
1. Edit
test_devices.ymlSelect the
device_typesyou wish to test. For each device, provide:ipusernamepasswordsecret(optional)
2. Edit
responses.ymlFor each
device_typedefined in your devices file, update the following fields to match your test device's behavior:base_promptrouter_promptenable_promptinterface_ip
Handle interactive command prompts using timing
developIf a command triggers a prompt that requires a delay-based response (e.g., a confirmation), use
send_command_timing(). This method relies on timing rather than pattern matching. You can usestrip_prompt=Falseandstrip_command=Falseto preserve the full interaction in the output.# Example of handling a 'confirm' prompt via timing output = net_connect.send_command_timing( command_string="del flash:/test3.txt", strip_prompt=False, strip_command=False ) if "confirm" in output: output += net_connect.send_command_timing( command_string="y", strip_prompt=False, strip_command=False )Enable Netmiko logging of all communications
developTo debug communications, you can enable Netmiko logging to capture all reads and writes of the communications channel. This requires configuring the standard Python
loggingmodule with aDEBUGlevel and targeting thenetmikologger.import logging logging.basicConfig(filename='test.log', level=logging.DEBUG) logger = logging.getLogger("netmiko")Connect via a terminal server using redispatch
developTo connect to an end device through a terminal server, use the
terminal_serverdevice_type. Because this type does not automatically handle the terminal server's interaction, you must manually manage the connection (sending commands likeconnect <id>and handling login prompts) usingwrite_channel()andread_channel(). Once you have successfully reached the end device's prompt, use theredispatch()function to dynamically reset thenet_connectobject to the correct device type (e.g.,cisco_ios) for standard Netmiko operations.from __future__ import unicode_literals, print_function import time from netmiko import ConnectHandler, redispatch net_connect = ConnectHandler( device_type='terminal_server', # Notice 'terminal_server' here ip='10.10.10.10', username='admin', password='admin123', secret='secret123') # Manually handle interaction in the Terminal Server # (fictional example, but hopefully you see the pattern) # Send Enter a Couple of Times net_connect.write_channel("\r\n") time.sleep(1) net_connect.write_channel("\r\n") time.sleep(1) output = net_connect.read_channel() print(output) # Should hopefully see the terminal server prompt # Login to end device from terminal server net_connect.write_channel("connect 1\r\n") time.sleep(1) # Manually handle the Username and Password max_loops = 10 i = 1 while i <= max_loops: output = net_connect.read_channel() if 'Username' in output: net_connect.write_channel(net_connect.username + '\r\n') time.sleep(1) output = net_connect.read_channel() # Search for password pattern / send password if 'Password' in output: net_connect.write_channel(net_connect.password + '\r\n') time.sleep(.5) output = net_connect.read_channel() # Did we successfully login if '>' in output or '#' in output: break net_connect.write_channel('\r\n') time.sleep(.5) i += 1 # We are now logged into the end device # Dynamically reset the class back to the proper Netmiko class redispatch(net_connect, device_type='cisco_ios') # Now just do your normal Netmiko operations new_output = net_connect.send_command("show ip int brief")Use encrypted values in YAML files
developWhen encryption is enabled in the
__meta__section, Netmiko automatically decrypts any field that starts with the__encrypt__prefix.Example format in YAML:
password: > __encrypt__<encrypted_payload_here>Set the NETMIKO_TOOLS_KEY environment variable
developNetmiko reads the encryption key from the
NETMIKO_TOOLS_KEYenvironment variable. This key must be a secure, randomly-generated value appropriate for your chosen encryption type (e.g., a Fernet key forfernetencryption).export NETMIKO_TOOLS_KEY="your-secure-key-here"Execute Netmiko tests using pytest
developNavigate to the
netmiko/testsdirectory to run the test suite. You must specify a--test_deviceflag, which corresponds to the device name defined in bothtest_devices.ymlandresponses.yml.Available test scripts:
test_netmiko_show.pytest_netmiko_config.pytest_netmiko_commit.py(Note: currently only supported for Juniper and IOS-XR)
cd ./netmiko/tests # Example: testing show commands on a cisco881 device py.test -v test_netmiko_show.py --test_device cisco881 # Example: testing configuration commands on a cisco881 device py.test -v test_netmiko_config.py --test_device cisco881