Introduction to Network Automation: Build Your First Backup Script with Python for a multi-vendor environment - Part 1

Welcome to the first post in our Network Automation series! If you're a network engineer who's been manually logging into devices to grab configurations, this post is for you. Today, we're diving into practical network automation by building a Python script that automatically backs up configurations from Nokia SROS, Cisco IOS and Juniper Junos devices.
By the end of this post, you'll have a working script that can save you hours of repetitive work and provide a solid foundation for your automation journey.
Why Network Automation?
Before we jump into code, let's address the elephant in the room: why automate?
Time Savings: Manually backing up 50 devices is time-consuming, taking hours, whereas automation completes the task in minutes.
Consistency: Scripts execute tasks without missing steps or making typographical errors.
Audit Trail: Automated backups with timestamps provide a dependable change history.
Disaster Recovery: Regular automated backups ensure preparedness for unforeseen events.
Scalability: As your network expands, automation prevents manual processes from becoming a bottleneck.
Why Coding is Essential for Network Engineers Today?
Modern networks are no longer configured on a device-by-device basis. They are software-driven systems. Acquiring coding skills enables network engineers to transition from manual operators to automation engineers.
Here’s what coding enables:
Automation Over Repetition
Instead of logging into 100 devices:
A script can push configs
Validate state
Roll back safely
Expedited Troubleshooting and Enhanced Visibility
With code, you can:
Pull live data from devices
Parse outputs (JSON/XML/YANG)
Detect anomalies automatically
Vendor-Agnostic Networking
Coding helps you think in models, not commands:
YANG models
OpenConfig
REST / NETCONF / gNMI
Career Longevity and Growth
Roles that increasingly expect coding skills:
Network Automation Engineer
NetDevOps Engineer
SRE (Network-focused)
Cloud Network Engineer
"You're either the one who creates the automation, or you're the one being automated." ~ Tom Preston-Werner, co-founder and former CEO of GitHub
Prerequisites
Before we begin, ensure you have:
Python 3.8 or higher installed
Basic understanding of Python (variables, functions, loops)
Access to network devices (lab or production)
SSH enabled on your network devices
Setting Up Your Environment
Step 1: Create a Virtual Environment
Virtual environments keep your project dependencies isolated and clean.
# Create a new directory for your project
mkdir network-automation
cd network-automation
# Create a virtual environment
python3 -m venv venv
# Activate the virtual environment
# On Linux/Mac:
source venv/bin/activate
# On Windows:
venv\Scripts\activate
Step 2: Install the Required Libraries
We'll use Netmiko , a popular Python library that simplifies SSH connections to network devices.
pip3 install netmiko
Step 3: Set Up a Lab Environment for Testing
In my testing environment, I am utilizing Containerlab. Containerlab is an open-source tool designed for creating network topologies with containerized network devices. It allows you to quickly set up multi-vendor network labs on your laptop without the need for hypervisors or heavy virtual machines, using only lightweight containers.
Multi-Vendor Network Topology:
Understanding Netmiko
Netmiko is a Python library that simplifies SSH connections to network devices, making it easier for network engineers to automate tasks without needing deep software engineering skills
Think of Netmiko as:
“SSH for network engineers, done the right way.”
What issues does Netmiko address?
When you manually SSH into a router, you must manage prompts, paging, privilege modes, and command timing on your own. Netmiko automates these processes. It is designed to interact seamlessly with devices from Nokia, Cisco, Juniper, Arista, HP, and many other vendors, eliminating the need to write custom code for each one.
Key features
Automatic handling of prompts: Knows when commands finish executing
Paging disabled: Automatically handles "-- More --" prompts
Multiple vendors: Just change
device_typeto support different platformsConfiguration mode: Built-in methods for entering config mode and sending commands
Error handling: Can detect command failures
Building Your First Backup Script
Version 1: Single Device Backup
Let's begin with a simple script to back up a single Nokia SROS device.
from netmiko import ConnectHandler
from datetime import datetime
import os
import sys
# Device details
nokia_device = {
'device_type': 'alcatel_sros',
'host': '172.20.20.13',
'username': 'admin',
'password': 'admin',
'timeout': 60, # Increased timeout for large configs
'session_log': 'netmiko_session.log' # Optional: log session for debugging
}
# Commands to execute
commands = [
'environment no more',
'admin display-config'
]
# Create backup directory if it doesn't exist
backup_dir = 'backups'
if not os.path.exists(backup_dir):
os.makedirs(backup_dir)
print(f"Created backup directory: {backup_dir}")
def validate_config(config_text):
"""Validate that configuration was retrieved successfully"""
if not config_text or len(config_text) < 100:
return False, "Configuration appears empty or too short"
# Check for common SR OS config indicators
if 'configure' not in config_text.lower():
return False, "Configuration doesn't appear to be valid SR OS config"
return True, "Configuration validated"
try:
# Connect to device
print(f"Connecting to {nokia_device['host']}...")
connection = ConnectHandler(**nokia_device)
print("Connected successfully")
# Get hostname for filename
hostname = connection.find_prompt().strip('#> ')
print(f"Device hostname: {hostname}")
# Execute commands
print("Setting terminal parameters...")
connection.send_command(commands[0], expect_string=r'#')
print(f"Retrieving configuration from {hostname}...")
config = connection.send_command(commands[1], expect_string=r'#', delay_factor=2)
# Validate configuration
is_valid, message = validate_config(config)
if not is_valid:
print(f"Warning: {message}")
response = input("Continue anyway? (y/n): ")
if response.lower() != 'y':
print("Backup cancelled")
connection.disconnect()
sys.exit(1)
else:
print(message)
# Create timestamp for filename
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
# Create filename
filename = f"{backup_dir}/{hostname}_{timestamp}.txt"
# Save configuration to file
with open(filename, 'w', encoding='utf-8') as f:
f.write(f"# Backup created: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
f.write(f"# Device: {hostname} ({nokia_device['host']})\n")
f.write(f"# {'='*60}\n\n")
f.write(config)
# Verify file was created and has content
file_size = os.path.getsize(filename)
print(f"Configuration saved to {filename}")
print(f"File size: {file_size:,} bytes")
# Disconnect
connection.disconnect()
print("Disconnected successfully")
except ConnectionError as e:
print(f"Connection error: {str(e)}")
print("Check network connectivity and device accessibility")
sys.exit(1)
except Exception as e:
print(f"An error occurred: {str(e)}")
print(f"Error type: {type(e).__name__}")
sys.exit(1)
print("\nBackup completed successfully!")
Expected Output
# Execute the script
python3 backup.py
Connecting to 172.20.20.13...
Connected successfully
Device hostname: *A:PE1
Setting terminal parameters...
Retrieving configuration from *A:PE1...
Configuration validated
Configuration saved to backups/*A:PE1_20260121_143523.txt
File size: 5,729 bytes
Disconnected successfully
Backup completed successfully!
What’s Next?
You now have a working understanding of SSH connections and basic command execution with Netmiko. In Part 2, we'll use these skills to build a practical script that backs up configurations from multiple devices automatically—the kind of task that saves network engineers hours every week. We will also breakdown the code step-by-step. Even if you've never programmed before, you'll understand exactly how it works.
By the end, you'll have a script that automatically backs up configurations from Nokia, Cisco, and Juniper devices!
Download the code
All the code from this post is available on GitLab: network-automation-week-1
Questions or Feedback?
Connect with me on LinkedIn. I'd love to hear about your automation journey!




