Hands-on tutorial

Tutorials · DevOps & Containers

How to Automate Switch Backups and Checks With Python and Netmiko

Write a small Python script that logs in to switches over SSH, saves running configurations with timestamps, runs show commands and reports failures, then schedule it securely.

Intermediate11 min7 steps

Before you start

  • Python 3 on a management server
  • SSH access to switches with a read-only or backup account
  • A Git repository or backup folder

Step by step

  1. Install Netmiko

    Create a virtual environment and install the library.

    python3 -m venv venv && . venv/bin/activate
    pip install netmiko
    
  2. Create an inventory

    List devices with their address and device type in a YAML or CSV file. Keep credentials out of the file; read them from environment variables or a vault.

  3. Write the backup script

    Connect to each device, run the command that shows the running configuration, and save it with the device name and date.

    from netmiko import ConnectHandler
    import os, datetime
    for dev in inventory:
        conn = ConnectHandler(device_type=dev['type'], host=dev['host'],
                              username=os.environ['NET_USER'], password=os.environ['NET_PASS'])
        cfg = conn.send_command('show running-config')
        open(f"backups/{dev['name']}.cfg", 'w').write(cfg)
        conn.disconnect()
    
  4. Handle failures

    Catch connection and authentication errors per device so one failure does not stop the run, and list failed devices at the end.

  5. Commit to Git

    Commit backups to a Git repository so you can see what changed and when.

  6. Schedule it

    Run the script nightly with cron or a systemd timer under a dedicated user.

  7. Add checks

    Extend the script with show commands, such as interface errors or PoE status, and send a summary by email or webhook.

Commands are generic, industry-standard examples. Exact syntax and menu names vary by model and firmware; check your device's manual on the Documentation page.

Pro tips

  • Use a dedicated read-only account for backups.
  • Protect the backup repository: configurations contain sensitive data.
  • Test restores from backups occasionally.