Multi-Device Config Backup
Multi-Device Configuration Backup¶
"From Read-Only to Read-and-Archive โ Capture Your Network's Source of Truth"¶
In Tutorial #1, you read show commands. In Tutorial #2, you scaled that to multiple devices. But here's the problem: show command output is temporary. If your network changes (intentionally or by mistake), that data is lost.
In this tutorial, we'll build on your multi-device foundation and create a production-grade backup system:
- Collect running configurations from multiple devices (not just show commands)
- Save each config to a timestamped backup file
- Organise configs by device type and hostname
- Handle errors gracefully (one failed backup doesn't stop others)
- Provide a backup inventory showing what was and wasn't captured
This is how you build audit trails and enable quick disaster recovery!
๐ฏ What You'll Learn¶
By the end of this tutorial, you'll understand:
- โ How to retrieve full running configurations from network devices
- โ Why timestamped backups are critical for change tracking
- โ How to organise backups in a logical directory structure
- โ The difference between running and startup configurations
- โ How to create a backup manifest (what was backed up, when, and from where)
- โ Per-device backup validation and error handling
- โ File I/O in Python and directory management
- โ How to prepare for configuration comparison and drift detection
๐ Prerequisites¶
Required Knowledge¶
- โ Completed Tutorial #2 โ This builds directly on that script
- โ Basic understanding of network configuration files
- โ Comfortable with Python file I/O operations
- โ Familiar with directory structures and file naming conventions
Required Software¶
Note: We use pandas and openpyxl only for the backup manifest. Configuration data is plain text files.
Required Access¶
- Multiple Cisco devices (2 or more) with:
- SSH enabled
- Same credentials (or per-device credentials)
- Reachable from your workstation
- Accessible user with privilege level 15 or equivalent (needed to read running config)
๐ Evolution from Tutorial #2¶
Here's what we're changing:
| Tutorial #2 (Show Commands) | Tutorial #3 (Configurations) |
|---|---|
| Executes show commands | Executes show run (running config) |
| Parses output with TextFSM | No parsingโraw config text |
| Exports to Excel sheets | Saves to timestamped .txt files |
| One Excel file with data | Organised folder structure with manifest |
| Shows data table | Shows backup file locations and sizes |
Key insight: Configurations are too large and complex for Excel. We save them as files and create a manifest for tracking.
๐ง The Complete Script¶
Here's the full backup script. We'll break down what changed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 | |
๐ Create Your Inventory File¶
Use the same CSV format as Tutorial #2. Create devices.csv:
๐ What Changed - Line by Line¶
Let's focus on what's different from Tutorial #2. We'll skip unchanged sections and highlight new concepts.
New Imports¶
What they do:
os: Provides functions to interact with the operating system (create directories, work with file paths)datetime: Allows us to generate timestamps for backup directories
Why: We need to create timestamped directories and write files to disk.
New Function: create_backup_directory()¶
This function is completely new:
What it does: Creates a directory structure like backups/20260215_143022/ for each backup run.
Why: Timestamped directories allow you to keep historical backups. You can compare configs from different dates and see exactly when changes occurred.
What it does: Gets the current date and time in format YYYYMMDD_HHMMSS (e.g., 20260215_143022).
Why: This creates unique, sortable directory names. Sorting by name sorts by time!
What it does: Joins path components safely.
Why: os.path.join() handles Windows vs. Unix path separators automatically. It's much better than manually concatenating strings with / or \.
Example output:
- Linux:
backups/20260215_143022 - Windows:
backups\20260215_143022
What it does: Creates the directory, handling errors gracefully.
Why:
os.makedirs()creates all intermediate directories (likemkdir -p)exist_ok=Truemeans "don't error if the directory already exists"- The try/except block catches permission errors or other filesystem issues
- If success, we return the path; if failure, we return
None
New Function: backup_device_config()¶
This is the core backup function:
What it does: Connects to ONE device, retrieves its running configuration, and saves it to a file.
Why: Similar to Tutorial #2's collect_from_device(), but instead of returning a DataFrame, we return file information. The function is designed to be called in a loop for multiple devices.
What it does: Stores device info and connects.
Why: Same pattern as Tutorial #2. We display the device_type so users know what they're connecting to.
What it does: Sends the show running-config command and gets the raw output.
Why: Key difference from earlier tutorials:
- No
use_textfsm=True: Running configs are text-based and don't need parsing - Raw text output: We keep it exactly as-is for archiving
What it does: Verifies we got configuration data.
Why: Unlike TextFSM-parsed data (which is a list), show running-config returns a string. We check it's not empty.
What it does: Creates a safe filename from the hostname.
Why:
- Filenames can't contain certain characters (like dots)
- Replacing
192.168.1.1with192-168-1-1makes the filename valid - The pattern
hostname_running-config.txtis clear and self-documenting
What it does: Creates a file and writes the configuration.
Why:
os.path.join()creates the full path (e.g.,backups/20260215_143022/192-168-1-1_running-config.txt)with open(...) as f:opens the file in a context manager (auto-closes even if error occurs)f.write(config)writes the entire configuration to the file
What it does: Gets the file size in bytes.
Why: File size is useful for sanity checks:
- If a large router backed up only 100 bytes, something's wrong
- Users can see at a glance which devices have large configs
What it does: Closes connection and returns success information.
Why: Returns a tuple with:
hostname: Which deviceconfig_filename: Filename (for reference)file_size: How much datastatus: 'success' (vs. 'failed' or 'no-data')
What it does: Catches any error and continues gracefully.
Why: Continue-on-error pattern from Tutorial #2. One device failure doesn't stop the whole backup.
New Function: create_backup_manifest()¶
This function creates an Excel summary of the backup operation:
What it does: Builds a list of dictionaries, one per device.
Why: Each dictionary becomes a row in the Excel manifest. The manifest acts as a backup inventoryโa record of what was backed up, when, and from where.
What it does: Converts the list of dictionaries to a pandas DataFrame.
Why: Makes it easy to export to Excelโsame pattern as Tutorial #1.
What it does: Saves the manifest to an Excel file in the backup directory.
Why: The manifest lives alongside the backups, providing metadata. Users can open it to see:
- Which devices succeeded/failed
- How large each device's config is
- When the backup ran
Updated main() Function¶
The main function orchestrates the entire backup operation:
What it does: Loops through devices and counts successes/failures.
Why:
resultscollects all backup operations (for the manifest)- Counters track success/failure for the summary report
- Similar pattern to Tutorial #2, but with status tracking
What it does: Lists all successful backups.
Why: User feedback. The {size:,} formats numbers with commas (e.g., 15,234 instead of 15234).
๐ How to Run the Script¶
Step 1: Create the Inventory CSV¶
Create devices.csv:
Step 2: Save the Script¶
Save the complete script as backup_running_configs.py
Step 3: Run the Script¶
Step 4: Enter Your Password¶
When prompted:
Type your password (it won't be displayed) and press Enter.
Step 5: Watch the Progress¶
You'll see output like:
Step 6: Verify Your Backups¶
After running, you'll see this directory structure:
Each .txt file contains the full running configuration from that device!
๐ Example Backup Directory Structure¶
After running backups multiple times, you'll have:
This structure makes it trivial to:
- Find the latest backup
- Compare configs across backup runs
- Identify when changes occurred
- Restore configs from any point in time
๐ Trying Different Configuration Sources¶
The script currently backs up show running-config. You can capture other config sources:
Just update the send_command() call and modify the filename accordingly.
๐ Key Concepts Learned¶
Congratulations! You've built a production-grade backup system. You now understand:
1. File I/O Operations¶
Reading configurations from devices and reliably writing them to disk with proper error handling.
2. Directory Structure and Organisation¶
Using timestamps to organise backups chronologically and creating logical directory hierarchies.
3. Backup Validation¶
Confirming that data was successfully written to disk by checking file sizes.
4. Manifest/Inventory Tracking¶
Creating audit trails (the Excel manifest) that record what was backed up, when, and the status.
5. Configuration Versioning¶
Organizing timestamped backups to enable version tracking and change detection.
6. Safe Filename Handling¶
Converting hostnames with special characters into valid filenames.
7. Multi-Step Operations¶
Combining several operations (connect, command, file write, validation) into a cohesive workflow.
๐ Troubleshooting¶
"Permission denied" when creating backup directory¶
Cause: You don't have write permissions in the directory where the script runs.
Solution:
- Try running from a different directory
- Use an absolute path:
base_backup_dir = 'C:/Backups'(Windows) or/tmp/backups(Linux) - Check file permissions on the current directory
Backup files are empty or very small¶
Causes:
- Device user doesn't have privilege level 15 (can't read full config)
- Device running-config is actually small (possible but unlikely)
- Command executed but returned no data
Solution:
- Verify your account has
privilege level 15or equivalent - Check manually with SSH:
show running-config | wc -lto see line count - Verify
show running-configworks manually on the device
"Authentication failed" for some devices¶
Cause: Those devices have different credentials.
Solution: See "Advanced Variations" below for per-device passwords.
Running the script multiple times is creating huge backup directories¶
Cause: Each run creates a new timestamped directory.
Solution: This is by design! Each run is a separate backup point. If you want to clean old backups:
Or implement retention policies (see "Advanced Variations").
๐ Advanced Variations¶
Per-Device Passwords¶
If devices have different passwords, use per-device credentials in CSV:
devices.csv with passwords:
Modified read_inventory() function:
Security Note: Storing passwords in CSV is NOT recommended for production. Use a vault (HashiCorp Vault, CyberArk, AWS Secrets Manager) instead.
Add Pre- and Post-Backup Hash Checking¶
Detect if config changed since last backup:
Then compare hashes in your manifest to detect changes!
Organise by Device Type¶
Save IOS configs separately from NX-OS:
Result:
Backup to Remote Server (SFTP)¶
Store backups on a remote backup server instead of local disk:
Backup Only if Config Changed¶
Compare current config with previous backup:
Email Notification on Backup Completion¶
Send status report via email:
Retention Policy (Auto-Delete Old Backups)¶
Keep only last 30 days of backups:
๐ฏ Next Steps¶
You've now built a complete backup system! Ready for the next challenge?
Continue Learning with These Tutorials:
- Complete the Learning Path:
-
You've completed the Beginner tutorials! You now understand Netmiko, multi-device connections, and data management.
-
Nornir Fundamentals (Intermediate)
- Learn a powerful framework used in enterprise automation
- Understand how to scale to thousands of devices
-
Master structured task execution
-
Enterprise Config Backup with Nornir (Intermediate)
- See this same backup pattern scaled to production
- Backup comparison and diff reporting
- Configuration drift detection and automated remediation
-
Encrypted backup storage and database-backed versioning
-
Advanced Nornir Patterns (Intermediate)
- Advanced filtering and task chaining
- Custom inventory sources
-
Integration with external systems
Study Production Code:
-
Deep Dives โ Review how production tools handle similar challenges
- CDP Network Audit โ Threading, security, and credential management
-
Access Switch Audit โ Parallel device collection and intelligent parsing
Ready to Deploy?
-
Script Library โ Deploy pre-built tools
-
Access Switch Audit for port configurations
-
Enhance This Script โ Practice by adding:
- Configuration comparison between backup runs
- Backup compression (ZIP files for storage efficiency)
- Progress bars using
tqdm - Logging to file with the
loggingmodule - Database storage of backup metadata
- Web interface to browse backups
๐ก Production Readiness Checklist¶
Want to use this script in production? Consider these enhancements:
๐ก Intermediate Level (Coming Soon in Tutorials)¶
- Configuration Comparison: Show what changed between backups
- Drift Detection: Alert when running config differs from startup
- Backup Compression: ZIP files to reduce storage
- Email Notifications: Status reports sent to admins
- Database Backend: Store config metadata and versions in SQLite/PostgreSQL
- Automated Cleanup: Delete backups older than retention period
- Conflict Resolution: Handle failed backups with retry logic
- Backup Verification: Spot-check that backups are not corrupted
- Version Tagging: Mark backups with change reasons ("Pre-maintenance", "Post-change", etc.)
- Selective Backup: Backup only specific devices or device types
- Change Tracking: Log when and why configs changed based on Git commits
- Config Sanitization: Remove sensitive data (passwords, private keys) before backup
๐ด Expert Level (Coming Soon in Tutorials)¶
- GitOps Integration: Auto-commit backups to Git, enable version control
- Configuration Compliance: Compare configs against standards/templates
- Netbox Integration: Backup device configs as source of truth
- Event-Driven Backup: Trigger immediately after detected changes
- Distributed Backup: Multi-location, replicated backup storage
- Automated Remediation: Detect drift and auto-remediate deviations
- Change Request Integration: ServiceNow tickets trigger backups
- Audit Trail: Full chain-of-custody for who accessed/modified backups
- API Exposures: REST API to query and restore backups
- Machine Learning: Anomaly detection for unexpected config changes
- Multi-Vendor Support: Backup Cisco, Arista, Juniper, Palo Alto configs
- Container Deployment: Docker-based scheduled backup service
- Testing & Validation: Automated tests verify backup integrity
- Cost Optimisation: Deduplication and incremental backups
These topics are covered in our Intermediate and Expert tutorials!
๐ฌ What You've Accomplished¶
Impressive! You've evolved from a single-device automation script to a enterprise-grade configuration backup system. You now understand:
โ
File I/O and directory management
โ
Configuration retrieval and archival
โ
Timestamped backup organisation
โ
Backup manifest creation
โ
Error handling and recovery
โ
Multi-device orchestration
โ
Audit trail creation
This foundation prepares you for configuration management, change detection, and compliance auditing at enterprise scale.
โ Back to Beginner Tutorials | Continue to Intermediate โ