HSR Sector 6 · Bangalore +91 96110 27980 Mon–Sat · 09:30–20:30
Chapter 9 of 20 — Python for Network Engineers
intermediate Chapter 9 of 20

SSH Automation — Multi-Device Config Push & Bulk Changes

By Vikas Swami, CCIE #22239 | Updated Mar 2026 | Free Course

Planning Bulk Changes — Inventory Files, Variables & Templates

Effective network config automation begins with meticulous planning, especially when performing SSH network automation multi-device tasks. The core challenge lies in managing configurations across multiple devices, which necessitates a structured approach to inventory management, variable handling, and template creation. This phase ensures repeatability, minimizes errors, and streamlines deployment.

Start by creating comprehensive inventory files that list all target devices. These files can be in formats such as CSV, YAML, or stored within a Configuration Management Database (CMDB). For example, a YAML inventory might look like:

devices:
  - hostname: switch1.example.com
    ip: 192.168.1.1
    device_type: cisco_ios
    vlan_id: 10
  - hostname: switch2.example.com
    ip: 192.168.1.2
    device_type: cisco_ios
    vlan_id: 20

Variables are central to customizing configurations per device. Using templating engines like Jinja2, variables such as VLAN IDs, interface names, or hostname prefixes can be dynamically inserted into configurations. Define a variables file, for example:

vlan_id: 10
hostname_prefix: SW

Templates serve as blueprints for configuration snippets. For instance, a VLAN creation template in Jinja2 might be:

configure terminal
vlan {{ vlan_id }}
 name VLAN{{ vlan_id }}
exit
hostname {{ hostname_prefix }}-{{ vlan_id }}

This approach enables bulk changes to be scaled efficiently, reducing manual effort and errors. Proper planning at this stage ensures that the automation process is robust, flexible, and adaptable to future requirements. For in-depth guidance on network automation planning, consider exploring courses at Networkers Home.

Reading Device Lists from CSV, YAML or a CMDB

Accurate device data is the backbone of SSH network automation multi-device workflows. Reading device details from external sources such as CSV, YAML, or a CMDB allows scalable and dynamic inventory management.

CSV Files: CSVs are simple and widely supported. An example CSV file might look like:

hostname,ip,device_type,vlan_id
switch1,192.168.1.1,cisco_ios,10
switch2,192.168.1.2,cisco_ios,20

Python's csv module or pandas library can parse CSV files efficiently. For example:

import csv
with open('devices.csv') as f:
    reader = csv.DictReader(f)
    for row in reader:
        print(row['hostname'], row['ip'])

YAML Files: YAML offers hierarchical structure, ideal for complex inventories. Example:

devices:
  - hostname: switch1
    ip: 192.168.1.1
    device_type: cisco_ios
    vlan_id: 10
  - hostname: switch2
    ip: 192.168.1.2
    device_type: cisco_ios
    vlan_id: 20

Python's PyYAML library simplifies parsing YAML files:

import yaml
with open('devices.yaml') as f:
    data = yaml.safe_load(f)
    for device in data['devices']:
        print(device['hostname'], device['ip'])

CMDB Integration: For large networks, integrating with a CMDB (Configuration Management Database) provides centralized management. APIs or database queries can extract device details dynamically, enabling real-time updates and reducing manual input errors.

By automating device list ingestion, network engineers can focus on high-level design rather than manual data entry, facilitating Networkers Home Blog for best practices in network automation.

Generating Per-Device Configs with Jinja2 Templates

Once device data and variables are loaded, the next step involves generating tailored configurations for each device using Jinja2 templating. This approach allows for scalable, consistent, and error-free config deployment, essential in SSH network automation multi-device scenarios.

Suppose you need to create VLAN configurations for multiple switches. The Jinja2 template might look like:

interface Vlan{{ vlan_id }}
 ip address 192.168.{{ vlan_id }}.1 255.255.255.0
 no shutdown
!
hostname {{ hostname_prefix }}-{{ vlan_id }}

Using Python, you can load device-specific variables and render the template accordingly:

from jinja2 import Environment, FileSystemLoader

env = Environment(loader=FileSystemLoader('templates'))
template = env.get_template('vlan_config.j2')

for device in devices:
    config = template.render(
        vlan_id=device['vlan_id'],
        hostname_prefix='SW'
    )
    with open(f"configs/{device['hostname']}_config.txt", 'w') as f:
        f.write(config)

This method ensures each device receives a configuration tailored to its parameters, vastly improving deployment efficiency and accuracy. The generated configs can then be pushed via SSH, utilizing tools like Netmiko, which simplifies multi-device SSH automation.

For detailed tutorials on config templating and automation workflows, visit Networkers Home.

Pushing Configs — send_config_from_file & Error Checking

Automated configuration deployment to multiple devices hinges on reliable SSH sessions and error handling. Python libraries like Netmiko facilitate this by providing methods such as send_config_from_file, which streamlines bulk config push operations.

Here's a typical workflow:

  1. Establish SSH connection to each device
  2. Send configuration commands from generated config files
  3. Implement error checking to verify successful execution

Example code snippet:

from netmiko import ConnectHandler

for device in devices:
    connection = ConnectHandler(
        device_type=device['device_type'],
        ip=device['ip'],
        username='admin',
        password='password'
    )
    try:
        output = connection.send_config_from_file(f"configs/{device['hostname']}_config.txt")
        if '%' in output:
            print(f"Error in device {device['hostname']}: {output}")
        else:
            print(f"Config pushed successfully to {device['hostname']}")
    except Exception as e:
        print(f"Failed to connect to {device['hostname']}: {str(e)}")
    finally:
        connection.disconnect()

Implementing robust error checking is vital for SSH network automation multi-device deployments, ensuring you can detect and rectify issues promptly. Using return codes, output parsing, and exception handling, network engineers can automate mass configuration with confidence.

Pre and Post-Change Validation — Comparing Outputs

Validation is a critical step in network config automation. It ensures that configurations are correctly applied and that network stability is maintained. Pre-change validation involves capturing the current device state, while post-change validation confirms the intended modifications.

Pre-change, execute commands like:

show running-config
show vlan brief
show version

Save these outputs for comparison. After deploying changes, re-run these commands to verify that configurations match expectations. Automated tools like Python scripts can parse CLI outputs and perform diff comparisons.

For example, using Python difflib:

import difflib

with open('pre_change_config.txt') as f1, open('post_change_config.txt') as f2:
    pre = f1.readlines()
    post = f2.readlines()

    diff = difflib.unified_diff(pre, post, fromfile='pre', tofile='post')
    for line in diff:
        print(line)

This process helps identify unintended changes or configuration drifts. For complex environments, network validation tools like Netmiko combined with scripting enable automated validation, reducing manual effort and errors.

Rollback Strategy — Saving Before and Restoring on Failure

In any automation process, especially involving multi-device SSH operations, a robust rollback plan is essential. Before pushing changes, back up current configurations to ensure quick restoration if needed.

Using Netmiko, backup commands like:

connection.send_command('show running-config') > backup_config.txt

Store these backups securely. If a deployment fails or causes network issues, restore previous configs with commands like:

connection.send_config_from_file('backup_config.txt')

Alternatively, for Cisco devices, use the copy running-config startup-config command or TFTP transfer methods for more comprehensive backups. Automating this process ensures minimal downtime and quick recovery, critical in enterprise environments.

Implementing transactional deployment—where changes are committed only after validation—further enhances reliability. Networkers Home’s courses emphasize these best practices for resilient automation strategies.

Parallel Execution — Threading for Speed with Safety

Executing SSH network automation multi-device operations sequentially can be slow, especially across large networks. Leveraging Python's threading or multiprocessing modules enables parallel deployment, significantly reducing downtime.

For example, using concurrent.futures:

import concurrent.futures
from netmiko import ConnectHandler

def deploy_config(device):
    try:
        connection = ConnectHandler(
            device_type=device['device_type'],
            ip=device['ip'],
            username='admin',
            password='password'
        )
        connection.send_config_from_file(f"configs/{device['hostname']}_config.txt")
        print(f"Configured {device['hostname']}")
    except Exception as e:
        print(f"Error configuring {device['hostname']}: {str(e)}")
    finally:
        connection.disconnect()

with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
    executor.map(deploy_config, devices)

While threading accelerates deployment, it must be used with caution: avoid overwhelming devices, manage SSH session limits, and implement error handling. Proper synchronization and error reporting are critical to prevent incomplete or inconsistent configurations.

Networkers Home’s training modules cover threading best practices, ensuring network engineers can automate efficiently without compromising network stability.

Practice: VLAN Deployment Across 20 Switches in 60 Seconds

To illustrate the power of automation, consider deploying a new VLAN across 20 switches. Traditionally, this task might take minutes per device, but automation can accomplish it in under a minute.

Here's a sample workflow:

  1. Prepare a VLAN configuration template in Jinja2.
  2. Generate device-specific configs from an inventory.
  3. Establish parallel SSH connections using threading.
  4. Push configs with error checking.
  5. Validate the deployment.

Sample script snippet:

# Load device list and template as shown earlier
# Generate configs
# Deploy in parallel
with concurrent.futures.ThreadPoolExecutor(max_workers=20) as executor:
    executor.map(deploy_config, devices)

In a real scenario, this approach reliably updates all switches within seconds, demonstrating how Networkers Home courses prepare you for such high-efficiency deployments.

Key Takeaways

  • Structured inventory management and templating are foundational to successful SSH network automation multi-device tasks.
  • Reading device data from CSV, YAML, or CMDB enables scalable, dynamic automation workflows.
  • Jinja2 templates facilitate per-device configuration generation, ensuring consistency and efficiency.
  • Using Netmiko's send_config_from_file simplifies bulk configuration deployment with integrated error checking.
  • Pre and post-validation, combined with rollback strategies, maintain network stability during automation.
  • Parallel execution via threading accelerates deployment without sacrificing safety, essential for large networks.
  • Practicing real-world scenarios like VLAN deployment demonstrates the tangible benefits of automation.

Frequently Asked Questions

How can I ensure safe rollback during bulk config pushes?

To guarantee safe rollback, always back up current device configurations before making changes. Use Netmiko or TFTP to save running configs externally. Implement transactional scripts that only commit changes after successful validation. In case of failure, restore previous configs via send_config_from_file or device-specific commands like copy startup-config. Automating these backups and restores minimizes downtime and prevents network disruptions during SSH network automation multi-device deployments.

What are best practices for error handling during multi-device SSH automation?

Proper error handling involves catching exceptions during SSH sessions, verifying command outputs for error messages, and logging failures for review. Use try-except blocks around connection and command executions. Implement checks for common CLI error indicators like '%' or 'Error' in responses. For large deployments, incorporate retries with exponential backoff and alerting mechanisms. These practices ensure reliable automation and quick troubleshooting, critical in complex networks managed through Networkers Home courses.

Can I automate configuration validation across multiple devices?

Yes, automation tools like Netmiko, NAPALM, or Ansible allow executing validation commands post-deployment. Scripts can capture outputs like 'show running-config' or 'show vlan brief' and compare them against expected configurations or previous backups. Automated diff checks identify discrepancies promptly. Incorporating validation into your automation workflow reduces manual audit efforts and ensures consistency across your network. For comprehensive training, consider the courses offered by Networkers Home.

Ready to Master Python for Network Engineers?

Join 45,000+ students at Networkers Home. CCIE-certified trainers, 24x7 real lab access, and 100% placement support.

Explore Course