Skip to content

Instantly share code, notes, and snippets.

@Tes3awy
Last active February 12, 2024 10:04
Show Gist options
  • Save Tes3awy/59daaa7660b685d8c2eac194a15976e4 to your computer and use it in GitHub Desktop.
Save Tes3awy/59daaa7660b685d8c2eac194a15976e4 to your computer and use it in GitHub Desktop.
A NAPALM Script to Gather All Configuration Types (Startup, Running, and Candidate if supported)
#!usr/bin/python3
# -*- coding: utf-8 -*-
import sys
from datetime import date
from napalm import get_network_driver
from napalm.base.exceptions import ConnectionException
from paramiko.ssh_exception import SSHException
from rich import print
devices = [
{
"hostname": "sandbox-iosxe-latest-1.cisco.com",
"username": "developer",
"password": "C1sco12345",
},
{
"hostname": "sandbox-iosxe-recomm-1.cisco.com",
"username": "developer",
"password": "C1sco12345",
},
]
configs = ["startup", "running", "candidate"]
# Define driver
driver = get_network_driver(name="ios")
# Iterate over devices
for device in devices:
try:
print(f"[magenta]Connecting to {device['hostname']}[/magenta]")
# Connect to device
with driver(**device) as conn:
prompt = conn.get_facts()["hostname"]
print(
f"[blue]Connected to {conn.hostname}:{conn.device.port} ({prompt})[/blue]"
)
for config_type in configs:
# Get configuration
config: str = conn.get_config(retrieve=config_type)[config_type]
# Name of config file
cfg_fname = f"{conn.hostname}-{config_type}-config_{date.today()}.txt"
# Check if config is not empty
if len(config):
# Save config to text file
with open(file=cfg_fname, mode="wt+", encoding="utf-8") as f:
f.write(config.lstrip())
print(
f"[green]Exported '{config_type}-config' of '{conn.hostname}' to '{cfg_fname}'[/green]"
)
else:
print(
f"[yellow]No '{config_type}-config' for '{conn.hostname}'[/yellow]"
)
except (SSHException, ConnectionException) as e:
print(
f"[red]Failed to connect to {device['hostname']} due to {type(e).__name__}",
file=sys.stderr,
)
else:
print(f"[cyan]Finished exporting configs for {conn.hostname}[/cyan]")
print("=" * 130, end="\n\n")
Connecting to sandbox-iosxe-latest-1.cisco.com
Connected to sandbox-iosxe-latest-1.cisco.com:22 (csr1000v-1)
Exported 'startup-config' of 'sandbox-iosxe-latest-1.cisco.com' to 'sandbox-iosxe-latest-1.cisco.com-startup-config_2022-01-02.txt'
Exported 'running-config' of 'sandbox-iosxe-latest-1.cisco.com' to 'sandbox-iosxe-latest-1.cisco.com-running-config_2022-01-02.txt'
No 'candidate-config' for 'sandbox-iosxe-latest-1.cisco.com'
Finished exporting configs for sandbox-iosxe-latest-1.cisco.com
==================================================================================================================================

Connecting to sandbox-iosxe-recomm-1.cisco.com
Failed to connect to sandbox-iosxe-recomm-1.cisco.com due to SSHException
napalm>=3.3.1
rich>=10.16.1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment