Write an SIE script with Netmiko
Netmiko is a Python library for SSH and Telnet to network devices. Its drivers know each platform’s prompts, pager, enable mode and login quirks, so a script just asks for a command’s output. It’s the quickest way to collect from an SSH CLI that a connection template can’t handle.
Good for
- SSH or Telnet CLIs on any of Netmiko’s supported platforms (platform list).
- Sessions that need enable mode, a pager answered, or a prompt that changes.
- Several commands in one session, such as moving between contexts.
Set it up
sudo python3 -m venv /opt/rconfig-sie/venv # oncesudo /opt/rconfig-sie/venv/bin/pip install netmikosudo chmod -R a+rX /opt/rconfig-siesudo -u apache /opt/rconfig-sie/venv/bin/python -c "import netmiko" # www-data on UbuntuThe command
The first argument is the Netmiko driver name:
/opt/rconfig-sie/venv/bin/python {script_path}my-netmiko.py cisco_ios {device_ip} {device_username} {device_password} {device_enable_password}A minimal script
#!/usr/bin/env python3"""Minimal SIE script with Netmiko.
Usage: netmiko-skeleton.py <device_type> <ip> <username> <password> [enable_password]"""
import sys
from netmiko import ConnectHandlerfrom netmiko.exceptions import NetmikoAuthenticationException, NetmikoTimeoutException
def fail(message): print(f"ERROR: {message}", file=sys.stderr) sys.exit(1)
def main(): if len(sys.argv) < 5: fail("usage: netmiko-skeleton.py <device_type> <ip> <username> <password> [enable_password]") device_type, host, username, password = sys.argv[1:5] secret = sys.argv[5] if len(sys.argv) > 5 else ""
try: with ConnectHandler(device_type=device_type, host=host, username=username, password=password, secret=secret, conn_timeout=20) as conn: if secret: conn.enable() config = conn.send_command("show running-config", read_timeout=90) except NetmikoAuthenticationException: fail(f"authentication failed for {username}@{host}") except NetmikoTimeoutException: fail(f"timed out connecting to {host}") except Exception as exc: fail(f"{type(exc).__name__}: {exc}")
if not config.strip(): fail(f"no output from {host}")
sys.stdout.write(config.rstrip("\n") + "\n") print(f"SIE-OK: netmiko {len(config.splitlines())} lines from {host}", file=sys.stderr) return 0
if __name__ == "__main__": sys.exit(main())Habits that matter with Netmiko
read_timeoutfor long output. It’s how longsend_commandwaits for the command to finish. A large config on a slow device needs more than the default.expect_stringwhen the prompt changes. After a command that changes the prompt (switching context, entering a shell), pass the new prompt as a pattern, then callset_base_prompt().- Keep
session_logoff in production. It records everything, including the password exchange. Use it to a file in/tmpwhile debugging, then remove it and the file.
Recipes that use Netmiko
- SSH backup with Netmiko
- Every context on a device
- Try again on a bad link (wrapping the Netmiko recipe)