Backing up configuration files from routers, switches, and firewalls is a routine yet critical task for any network team. Doing it manually is time‑consuming and error‑prone, especially when you have dozens or hundreds of devices. In this guide we’ll walk you through building a reliable, Python‑powered backup solution that can run on a schedule, store backups safely, and alert you when something goes wrong. By the end you’ll have a reusable script, a simple inventory file, and a handful of best‑practice tips to keep your network’s configuration data safe.
What You’ll Need
- Python 3.8+ installed on a Linux, macOS, or Windows machine
- Administrative SSH access to each network device you want to back up
- Python libraries:
netmiko,paramiko, andpyyaml - A writable directory for storing backup files (e.g.,
/var/backups/net-configs) - Optional: Git or another version‑control system for change tracking
Step 1: Set Up Your Python Environment
First, create an isolated virtual environment so the required packages don’t clash with other projects. Open a terminal and run:
python3 -m venv netbackup-env
source netbackup-env/bin/activate # On Windows use netbackup-envScriptsactivate
pip install --upgrade pip
pip install netmiko pyyaml
We use netmiko because it abstracts away the quirks of different vendor CLI prompts, while pyyaml lets us keep device inventory in a clean, human‑readable format.
Step 2: Create a Device Inventory File
Store all devices you want to back up in a YAML file (e.g., inventory.yml). Each entry should include the device’s IP, type, and login credentials. Here’s a minimal example:
devices:
- name: core‑router‑01
host: 10.0.0.1
platform: cisco_ios
username: admin
password: secret123
- name: edge‑switch‑02
host: 10.0.0.12
platform: cisco_ios
username: admin
password: secret123
- name: fw‑branch‑01
host: 10.0.1.5
platform: juniper
username: admin
password: secret123
Keep this file out of public repositories or encrypt it with a tool like ansible‑vault if you need to share the script.
Step 3: Write the Backup Script
Below is a fully commented Python script (backup.py) that reads the inventory, connects to each device, pulls the running configuration, and writes it to a timestamped file.
#!/usr/bin/env python3
import os
import sys
import yaml
import datetime
from netmiko import ConnectHandler
# ---------- Configuration ----------
INVENTORY_FILE = 'inventory.yml'
BACKUP_ROOT = '/var/backups/net-configs' # Change to your preferred path
RETENTION_DAYS = 30 # Keep files for 30 days
# ---------- Helper Functions ----------
def load_inventory(path):
with open(path) as f:
data = yaml.safe_load(f)
return data.get('devices', [])
def make_backup_dir(base, device_name):
today = datetime.datetime.now().strftime('%Y-%m-%d')
dir_path = os.path.join(base, device_name, today)
os.makedirs(dir_path, exist_ok=True)
return dir_path
def save_config(dir_path, config):
timestamp = datetime.datetime.now().strftime('%H%M%S')
filename = f'running-config-{timestamp}.txt'
full_path = os.path.join(dir_path, filename)
with open(full_path, 'w') as f:
f.write(config)
return full_path
def prune_old_backups(base, days):
cutoff = datetime.datetime.now() - datetime.timedelta(days=days)
for root, _, files in os.walk(base):
for f in files:
full_path = os.path.join(root, f)
mtime = datetime.datetime.fromtimestamp(os.path.getmtime(full_path))
if mtime < cutoff:
os.remove(full_path)
print(f'Deleted old backup: {full_path}')
# ---------- Main Logic ----------
if __name__ == '__main__':
devices = load_inventory(INVENTORY_FILE)
if not devices:
sys.exit('No devices found in inventory.')
for dev in devices:
try:
conn = ConnectHandler(**dev)
# The command differs per vendor; Netmiko abstracts this with .send_command()
if dev['platform'] in ['cisco_ios', 'cisco_xe']:
output = conn.send_command('show running-config')
elif dev['platform'] == 'juniper':
output = conn.send_command('show configuration')
else:
output = conn.send_command('show running-config')
backup_dir = make_backup_dir(BACKUP_ROOT, dev['name'])
saved_path = save_config(backup_dir, output)
print(f'Successfully backed up {dev["name"]} to {saved_path}')
except Exception as e:
print(f'ERROR: Could not backup {dev.get("name", dev.get("host"))}: {e}')
finally:
if 'conn' in locals():
conn.disconnect()
# Clean up old backups
prune_old_backups(BACKUP_ROOT, RETENTION_DAYS)
Save the script, make it executable (chmod +x backup.py), and run it manually first to verify everything works.
Step 4: Schedule the Script with Cron (or Task Scheduler)
Automation loses its value if you still have to launch the script by hand. On Linux/macOS, add a cron entry that runs the script nightly:
# Edit the crontab for the user that owns the backup directory
crontab -e
# Add the following line (runs at 02:30 AM every day)
30 2 * * * /path/to/netbackup-env/bin/python /path/to/backup.py >> /var/log/netbackup.log 2>&1
If you’re on Windows, create a Task Scheduler job that triggers python C:pathtobackup.py on your desired schedule. Remember to point the task to the virtual‑environment’s python.exe.
Step 5: Version Control and Alerting (Optional but Recommended)
Storing raw text files is fine, but adding a Git repository gives you instant diffing, history, and the ability to roll back. Initialise a repo inside the backup root:
cd /var/backups/net-configs
git init
git config user.name "Backup Bot"
git config user.email "[email protected]"
Modify save_config in the script to automatically commit after each run:
def commit_backup(repo_path, device, file_path):
import subprocess
subprocess.run(['git', '-C', repo_path, 'add', file_path], check=True)
msg = f"Backup {device} {datetime.datetime.now().isoformat()}"
subprocess.run(['git', '-C', repo_path, 'commit', '-m', msg], check=True)
Call commit_backup(BACKUP_ROOT, dev['name'], saved_path) after save_config. For alerting, you can pipe the script’s output to mail, Slack webhook, or a simple sendmail call when an exception occurs.
Common Mistakes to Avoid
Even a well‑written script can fail if you overlook these pitfalls:
- Hard‑coding credentials. Store passwords in a vault or use environment variables. Hard‑coded secrets are a security nightmare.
- Ignoring device‑specific commands. Not all vendors use
show running-config. Test each platform’s command before scaling. - Insufficient error handling. A single failed SSH connection can abort the whole run. Wrap each device loop in a
try/exceptas shown. - Running the script as root. Only the backup directory needs write permissions. Running as root expands the attack surface.
- Not rotating old backups. Disk space fills up quickly. The
prune_old_backupsfunction prevents that.
Tips and Tricks
Take the script a step further with these enhancements:
- Parallelism. Use
concurrent.futures.ThreadPoolExecutorto back up dozens of devices simultaneously, cutting total runtime dramatically. - Dynamic inventory. Pull device lists from NetBox, SolarWinds, or an internal CMDB via API instead of a static YAML file.
- Configuration diff alerts. After committing to Git, run
git diff --quiet HEAD~1 HEAD. If there’s a diff, send a notification with the changed lines. - Encrypt backups. Pipe the config through
gpgbefore writing to disk if you need at‑rest encryption. - Use SSH keys. Configure key‑based auth and disable password logins on devices for stronger security.
Frequently Asked Questions
Can I use this script for non‑Cisco devices?
Absolutely. Netmiko supports over 150 platforms. Just add the correct platform value in the inventory and adjust the command inside the script if the vendor uses a different syntax.
What if a device is unreachable during the scheduled run?
The script logs the error and moves on to the next device. To be notified, redirect the script’s output to an email or Slack channel, or integrate a monitoring tool like Zabbix to watch the log file.
How do I restore a configuration from a backup?
Copy the desired backup file to the device using the appropriate CLI command (copy tftp: running-config, load merge for Juniper, etc.). If you stored backups in Git, you can checkout a previous commit and push that file to the device.
Conclusion
Automating network device backups with Python eliminates tedious manual steps, reduces human error, and gives you a searchable history of every change. By following the five steps above—setting up a clean environment, defining a structured inventory, writing a robust script, scheduling it, and optionally version‑controlling the results—you’ll have a production‑ready solution that scales with your network. Keep an eye on the common mistakes, apply the tips, and you’ll spend less time chasing missing configs and more time focusing on what really matters: keeping the network up and running.
Photo by Taylor Vick on Unsplash






