Skip to content
Website under migration: We are moving to a new design. Some pages may look different or load slowly for a few days. Thank you for your patience.
SwitchFirewall
IPv4 Detecting…
IPv6 Detecting…

Automate Cisco Switch Configuration and Backup with Python

Last updated:

Introduction

The ever-growing complexity of network infrastructure demands a shift from manual configuration to automation. Network automation with Python scripts offers a powerful solution, streamlining network management tasks and boosting efficiency. This blog post dives into using Paramiko, a Python library, to connect and configure Cisco devices, laying the foundation for automating various network management processes.

Why Automate Network Device Configuration?

Manual network configuration is a time-consuming and error-prone process. Automating with Python scripts brings several advantages:

Getting Started with Python and Paramiko

To embark on your network automation journey with Python, you'll need the following:

  1. Python: Download and install the latest version of Python from https://www.python.org/downloads/.
  2. Text Editor or IDE: Choose a text editor like Visual Studio Code or a full-fledged Integrated Development Environment (IDE) like PyCharm for writing and running Python code.
  3. Paramiko Library: Install the Paramiko library using pip install paramiko in your terminal. This library facilitates secure SSH communication with network devices, including Cisco devices.

Once you have these tools in place, let's explore the basics of connecting to a Cisco device with Paramiko.

Connecting to Cisco Devices with Paramiko

Here's a Python script demonstrating how to connect to a Cisco router using Paramiko (similar to the provided script): 

Python Code:

import paramiko
import time
import getpass
import datetime
import os.path
import os
from datetime import datetime
def check_switch(ip):
 response = os.system("ping -c 1 " + ip) # Ping the IP address
 return response == 0 # Returns True if the IP is reachable, False otherwise
def main():
 timestr = datetime.now().strftime("%H")
 my_dir = "D:\Python"
 fname = os.path.join(my_dir, timestr)
 # Get Username and Password
 username = "cisco" # Enter Username
 password = getpass.getpass("Enter Password:")
 # Open file with list of switches
 with open("myswitches.txt") as f:
 for line in f:
 ip_address = line.strip()
 if not check_switch(ip_address):
 print(f"{ip_address} is not accessible. Moving to the next IP...")
 continue
 try:
 ssh_client = paramiko.SSHClient()
 ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
 ssh_client.connect(hostname=ip_address, username=username, password=password)
 print("Successful connection to", ip_address)
 remote_connection = ssh_client.invoke_shell()
 remote_connection.send("terminal length 0\n")
 remote_connection.send("show running-config\n")
 remote_connection.send("show interfaces description\n")
 remote_connection.send("show interfaces status\n")
 remote_connection.send("show vlan brief\n")
 remote_connection.send("show inventory\n")
 remote_connection.send("show version\n")
 remote_connection.send("exit\n")
 time.sleep(10)
 readoutput = remote_connection.recv(655350)
 saveoutput = open(f"{fname}_{ip_address}.txt", "wb")
 saveoutput.write(readoutput)
 print("Successful saved")
 saveoutput.close()
 ssh_client.close()
 except Exception as e:
 print(f"An error occurred while connecting to {ip_address}: {e}")
if __name__ == "__main__":
 main()
 

Explanation of the Provided Python Script for Network Automation

This Python script utilizes Paramiko to automate connecting to Cisco devices and collecting configuration information. Here's a breakdown of its functionalities:

  1. Imports:
  1. check_switch Function:
  1. main Function:
  1. Username and Password:
  1. Processing Switches from a File:
  1. Connecting to the Switch:
  1. Sending Commands and Collecting Output:
  1. Saving Output to a File:
  1. Closing the Connection:
  1. Exception Handling:

Conclusion:

using Python scripts to automate network device settings makes managing networks easier and more accurate. It helps reduce mistakes and allows teams to concentrate on important tasks, Adopting this approach can result in improved network performance and a more dependable system overall.