Day 3- Automating 100 Network Device Backups with Python

In today's fast-paced IT environment, ensuring that network configurations are backed up regularly is crucial. A simple misconfiguration or hardware failure can lead to outages. Having backups allows for quick restoration and peace of mind. In this blog post, we'll explore how to automate the backup of network device configurations using Python.

Why Automate Network Backups?

  1. Consistency: Ensure all devices are backed up regularly without missing any.

  2. Efficiency: Reduce manual effort and potential human errors.

  3. Scalability: Easily scale to hundreds or thousands of devices.

Real World scenario

TechFusion Corp., a rapidly growing tech startup, recently expanded its network infrastructure to support its increasing number of employees and clients. With over 150 network devices, including routers, switches, and firewalls, the IT team faced a daunting challenge: ensuring that each device's configuration was backed up regularly. Manual backups were time-consuming, error-prone, and simply not scalable.

Jane, the lead network engineer at TechFusion, recognized the potential risks. A misconfiguration or hardware failure without a recent backup could lead to significant downtime, affecting both employees and clients. She decided that automation was the way forward.

Prerequisites:

  • Python installed on your machine.

  • netmiko library installed (pip install netmiko).

  • Access to network devices for testing.

  • FTP server for storing backups.

Step-by-Step Guide:

1. Organizing Device Details:

Instead of hardcoding device details in our script, we'll use a separate devices.txt file. This approach is scalable and maintainable.

devices.txt format:

# device_type,ip,username,password,secret
cisco_ios,192.168.1.1,admin,password,secret
cisco_ios,192.168.1.2,admin,password,secret
# ... add more devices as needed

2. The Python Script:

Our script, named backup_configs.py, will do the following:

  • Read device details from devices.txt.

  • Connect to each device and fetch the running configuration.

  • Save the configuration with a timestamp.

  • Upload the configuration to an FTP server.

backup_configs.py:

from netmiko import ConnectHandler
from datetime import datetime
import os
import csv

def backup_config(device):
    connection = ConnectHandler(**device)
    config = connection.send_command("show running-config")
    connection.disconnect()

    filename = f"{device['ip']}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.cfg"
    with open(filename, 'w') as file:
        file.write(config)

    # Upload to FTP
    os.system(f"curl -T {filename} ftp://YOUR_FTP_USERNAME:YOUR_FTP_PASSWORD@ftp.cisco.com/vikas/")
    os.remove(filename)  # Remove the local backup file after uploading

if __name__ == "__main__":
    devices = []

    with open('devices.txt', 'r') as file:
        reader = csv.reader(file)
        for row in reader:
            if row[0].startswith("#"):  # Skip comments
                continue
            device = {
                'device_type': row[0],
                'ip': row[1],
                'username': row[2],
                'password': row[3],
                'secret': row[4],
            }
            devices.append(device)

    for device in devices:
        backup_config(device)

Replace the FTP placeholders with your credentials.

3. Scheduling the Backup:

To ensure our backups are taken daily at 6pm:

  • Linux: Use cron. Add the following line to your crontab (crontab -e):

      0 18 * * * /usr/bin/python3 /path/to/backup_configs.py
    
  • Windows: Use Task Scheduler. Create a new task to run the script daily at 6pm.

Security Considerations:

  • Sensitive Data: The devices.txt file contains sensitive information. Ensure it's secured and has restricted access.

  • FTP Security: Using plain FTP can expose data. Consider using SFTP or FTPS for encrypted transfers.

  • Credential Storage: Storing FTP credentials in the script isn't secure. Consider environment variables or secure vaults.

Conclusion:

Automating network backups is a step towards a resilient and efficient network infrastructure. With Python and a few lines of code, we've created a scalable solution that can be adapted to various environments. Always test in a lab setup before deploying in a production environment. Happy automating!