Skip to content
Guides & References

Back up an SSH device with Netmiko

An SIE recipe that collects a running config with Python and Netmiko, for SSH devices whose login or paging a connection template struggles with.

Script Integration EngineUpdated
On this page

Back up an SSH device with Netmiko

This recipe hands the SSH session to Netmiko, a Python library with drivers for a long list of network operating systems. The driver deals with the device’s login screens, pager and prompt, and the script prints the running config. One script covers every platform Netmiko supports: you change one argument in the command.


When to use it

Use a connection template first. It needs no code. Reach for this recipe when a template can’t get a clean session on a device but Netmiko has a driver for it, for example:

  • a “Press any key to continue” screen before the login prompt, as on HPE ProCurve and Aruba-OS switches (hp_procurve);
  • a pager that can’t be turned off and needs answering on every page;
  • a prompt that changes in ways a template’s prompt matching can’t follow.

Netmiko’s platform list shows the driver names to use.


What you need

  • Netmiko installed in a virtual environment the web user can read. Get your server ready for scripts shows how; the commands below assume /opt/rconfig-sie/venv.
  • The device’s username and password, and enable password if it has one, on its rConfig device record.

The template

sie-netmiko-template.yml
main:
name: "SIE - Netmiko backup"
desc: "Collects the running config through Netmiko"
connect:
timeout: 120 # Large configs on slow devices take a while
idletimeout: 90 # Netmiko prints nothing while it reads a long config
idleTimeout: 90
protocol: script
# exit_codes is deliberately left out: any non-zero exit fails the run.
failure_criteria:
error_patterns:
- "ERROR:"
success_patterns:
- "SIE-OK: netmiko"

The command

Add this to the device’s command group. The first argument after the script is the Netmiko driver name:

/opt/rconfig-sie/venv/bin/python {script_path}netmiko-backup.py hp_procurve {device_ip} {device_username} {device_password} {device_enable_password}

{device_enable_password} comes last on purpose. On a device with no enable password it is empty, and an empty value anywhere else would move the other arguments (see how your script talks to rConfig).


The script

Save it as netmiko-backup.py in the scripts folder.

netmiko-backup.py
#!/usr/bin/env python3
"""Collect a running config through Netmiko for the rConfig Script Integration Engine.
Usage:
netmiko-backup.py <device_type> <ip> <username> <password> [enable_password]
The config goes to stdout and becomes the stored backup. Progress, errors and the
success marker go to stderr. Exit code 0 on success, 1 on any failure.
"""
import sys
from netmiko import ConnectHandler
from netmiko.exceptions import NetmikoAuthenticationException, NetmikoTimeoutException
# The command that prints the config, per Netmiko driver. Add your platforms here.
CONFIG_COMMANDS = {
"hp_procurve": "show running-config",
"aruba_os": "show running-config",
"cisco_ios": "show running-config",
"cisco_nxos": "show running-config",
"fortinet": "show full-configuration",
"juniper_junos": "show configuration | display set",
}
# Lines that change on every run without the config changing.
VOLATILE_PREFIXES = (
"Building configuration",
"Current configuration :",
"! Last configuration change",
"! NVRAM config last updated",
)
def note(message):
print(message, file=sys.stderr)
def fail(message):
print(f"ERROR: {message}", file=sys.stderr)
sys.exit(1)
def main():
if len(sys.argv) < 5:
fail("usage: netmiko-backup.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 ""
command = CONFIG_COMMANDS.get(device_type)
if command is None:
fail(f"no config command defined for device type '{device_type}'")
device = {
"device_type": device_type,
"host": host,
"username": username,
"password": password,
"secret": secret,
"conn_timeout": 20,
}
note(f"connecting to {host} as {username} ({device_type})")
try:
with ConnectHandler(**device) as conn:
if secret:
conn.enable()
output = conn.send_command(command, 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: # anything else Netmiko or the transport raises
fail(f"{type(exc).__name__}: {exc}")
lines = [
line
for line in output.splitlines()
if not line.strip().startswith(VOLATILE_PREFIXES)
]
if not any(line.strip() for line in lines):
fail(f"'{command}' returned no output, refusing to store an empty config")
sys.stdout.write("\n".join(lines) + "\n")
note(f"SIE-OK: netmiko {device_type} {len(lines)} lines from {host}")
return 0
if __name__ == "__main__":
sys.exit(main())

What gets stored

Only the device’s config, without the lines that change on every run. For an HPE ProCurve switch it looks like this:

; J9773A Configuration Editor; Created on release #YA.16.10.0010
hostname "sw-access-01"
module 1 type j9773a
snmp-server community "example-community" restricted
vlan 1
name "DEFAULT_VLAN"
untagged 1-24
ip address 192.0.2.21 255.255.255.0
exit

The indentation under vlan 1 is gone because rConfig trims every stored line. That is expected, and the config still diffs and searches cleanly.


Adapting it

  • Another platform. Change the first argument in the command, and add the driver and its config command to CONFIG_COMMANDS if it isn’t there.
  • More than one command. Make a second command in the command group with a different driver command, or extend the script to print several outputs with a fixed ===== command ===== line between them, as the snapshot recipe does.
  • SSH keys instead of passwords. Netmiko accepts use_keys and key_file. Keep the key in the scripts keys folder.
  • More noise to remove. Add prefixes to VOLATILE_PREFIXES, or see the cleaning output recipe.

Type to search.