Network Automation with Python

networking
python
automation
Published

March 31, 2026

OSPF Configuration Script

Here’s a Python script for automating OSPF configuration on Cisco devices:

from netmiko import ConnectHandler
import json

def configure_ospf(device_params, ospf_config):
    """
    Configure OSPF on a Cisco device
    
    Args:
        device_params (dict): Device connection parameters
        ospf_config (dict): OSPF configuration parameters
    """
    
    # Connect to device
    connection = ConnectHandler(**device_params)
    
    # Build configuration commands
    commands = [
        f"router ospf {ospf_config['process_id']}",
        f"router-id {ospf_config['router_id']}",
    ]
    
    # Add network statements
    for network in ospf_config['networks']:
        commands.append(f"network {network['subnet']} {network['wildcard']} area {network['area']}")
    
    # Send configuration
    output = connection.send_config_set(commands)
    connection.disconnect()
    
    return output

# Example usage
device = {
    'device_type': 'cisco_ios',
    'host': '192.168.1.1',
    'username': 'admin',
    'password': 'password'
}

ospf_params = {
    'process_id': 1,
    'router_id': '1.1.1.1',
    'networks': [
        {'subnet': '10.0.0.0', 'wildcard': '0.0.0.255', 'area': 0},
        {'subnet': '172.16.0.0', 'wildcard': '0.0.255.255', 'area': 1}
    ]
}

result = configure_ospf(device, ospf_params)

Mathematical Analysis

The OSPF shortest path calculation uses Dijkstra’s algorithm with complexity:

\[O((V + E) \log V)\]

Where: - \(V\) = number of vertices (routers) - \(E\) = number of edges (links)

Bash Automation

#!/bin/bash
# Backup network configurations

DEVICES=("router1" "router2" "switch1")
BACKUP_DIR="/backups/$(date +%Y%m%d)"

mkdir -p "$BACKUP_DIR"

for device in "${DEVICES[@]}"; do
    echo "Backing up $device..."
    ssh admin@$device "show running-config" > "$BACKUP_DIR/${device}_config.txt"
    
    if [ $? -eq 0 ]; then
        echo "✓ $device backup completed"
    else
        echo "✗ $device backup failed"
    fi
done

JSON Configuration Template

{
  "ospf": {
    "process_id": 1,
    "router_id": "1.1.1.1",
    "areas": [
      {
        "area_id": 0,
        "type": "backbone",
        "networks": ["10.0.0.0/24", "192.168.1.0/24"]
      },
      {
        "area_id": 1,
        "type": "standard",
        "networks": ["172.16.0.0/16"]
      }
    ]
  }
}