Automatically Schedule to Backups Cisco Routers and Switches using Python Network Automation

Automatically Schedule to Backups Cisco Routers and Switches using Python Network Automation

Description: In today’s fast-paced networking environment, automating routine tasks like configuration backup is essential for efficient network management. Our latest Python script, powered by Paramiko, offers a seamless solution for automating Cisco configuration backup and transfer.

Using SSH, the script connects to Cisco devices, retrieves their running configurations, and uploads them to an SFTP server. By leveraging the power of automation, network administrators can save time, ensure consistency, and enhance security across their network infrastructure.

In our comprehensive WordPress post, we dive deep into the script’s functionality, guiding you through the steps to set up and schedule automated configuration backup tasks. From reading router information from a CSV file to scheduling the main function to run at regular intervals using the schedule library, we cover it all.

Whether you’re a seasoned network administrator or a Python enthusiast looking to streamline network management tasks, our WordPress post has something for everyone. Join us as we explore the world of network automation and empower you to take control of your Cisco configurations with ease.

 

For running hourly:

schedule.every().hour.do(main)

For running daily:

schedule.every().day.at("00:00").do(main)

For running weekly on a specific day and time:

schedule.every().monday.at("10:00").do(main) # Example: Every Monday at 10:00 AM

For running bi-weekly:

schedule.every(2).weeks.do(main)

For running monthly on a specific day and time:

schedule.every().month.at("12:00").do(main) # Example: Every month at 12:00 PM on the 1st day of the month

Here is the full script:

import csv
import paramiko
import time
import schedule

def get_cisco_config(hostname, username, password, enable_password):
    try:
        # Connect to the Cisco device using SSH
        ssh_client = paramiko.SSHClient()
        ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh_client.connect(hostname, username=username, password=password)

        # Create a shell session
        shell = ssh_client.invoke_shell()

        # Send enable command
        shell.send("enable\n")
        time.sleep(1)
        shell.send(enable_password + "\n")

        # Send command to retrieve running configuration
        shell.send("ter len 0\n")  # Setting up terminal length as 0
        shell.send("show running-config\n")

        # Wait for the command to execute
        time.sleep(1)

        # Read the output of the command
        output = ""
        while shell.recv_ready():
            output += shell.recv(1024).decode()

        # Close SSH connection
        ssh_client.close()

        return output

    except Exception as e:
        print(f"Error retrieving configuration from {hostname}: {e}")
        return None

def upload_to_sftp(server, username, password, local_path, remote_path):
    try:
        # Establish an SFTP connection to the server
        transport = paramiko.Transport((server, 22))
        transport.connect(username=username, password=password)
        sftp = paramiko.SFTPClient.from_transport(transport)

        # Upload the file
        sftp.put(local_path, remote_path)

        # Close SFTP connection
        sftp.close()

        print(f"Configuration uploaded to {server} at {remote_path}")

    except Exception as e:
        print(f"Error uploading configuration to {server}: {e}")

def main():
    # Read router information from CSV file
    routers = []
    with open('router_info.csv', 'r') as csvfile:
        csv_reader = csv.reader(csvfile)
        next(csv_reader)  # Skip the header row
        for row in csv_reader:
            routers.append({
                "hostname": row[0],
                "username": row[1],
                "password": row[2],
                "enable_password": row[3]
            })

    # SFTP server credentials
    sftp_server = "172.16.0.101"  # IP address of the SFTP server
    sftp_username = "cisco"  # Username for accessing the SFTP server
    sftp_password = "cisco"  # Password for accessing the SFTP server

    for router in routers:
        config = get_cisco_config(router["hostname"], router["username"], router["password"], router["enable_password"])
        if config:
            # Save running configuration to a local file
            local_path = f"running_config_{router['hostname']}.txt"
            with open(local_path, "w") as f:
                f.write(config)

            # Upload the running configuration to SFTP server
            upload_to_sftp(sftp_server, sftp_username, sftp_password, local_path, f"/running_config_{router['hostname']}.txt")

# Schedule the main function to run every minute
schedule.every(1).minutes.do(main)

# Infinite loop to keep the script running
while True:
    schedule.run_pending()
    time.sleep(1)  # Wait for 1 second before checking the schedule again


 

Here is the YouTube video:

Stay tuned for our step-by-step guide and unlock the power of automation in your network management workflow!

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *