Automating Network Device Configuration with Python Scripts

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:

  • Increased Efficiency: Automating repetitive tasks like configuration changes frees up valuable time for network engineers to focus on strategic planning and optimization.
  • Reduced Errors: Script-based configuration eliminates human error, ensuring consistent and accurate configurations across your network devices.
  • Improved Scalability: Managing large networks becomes easier with automated configuration. Scripts can be easily adapted to handle multiple devices, saving time and effort.
  • Enhanced Consistency: Automating configuration guarantees consistent settings across devices, leading to improved network performance and manageability.
  • Simplified Reporting: Scripts can generate automated reports on network configuration and health, providing valuable insights for troubleshooting and optimization.

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:
  • paramiko: Enables secure SSH communication with network devices.
  • time: Used for pausing the script execution for a brief period.
  • getpass: Provides a secure way to prompt the user for password input.
  • datetime: Used for generating timestamps for filenames.
  • os.path: Provides functions for manipulating file paths.
  • os: Used for interacting with the operating system (ping command in this case).
  1. check_switch Function:
  • This function takes an IP address as input.
  • It uses os.system("ping -c 1 " + ip) to ping the provided IP address with one count (verifying reachability).
  • The function returns True if the ping is successful (device is reachable), otherwise it returns False.
  1. main Function:
  • This is the main execution block of the script.
  • It first gets the current hour using datetime.now().strftime("%H") and stores it in timestr. This will be used for creating unique filenames.
  • my_dir defines the directory path where configuration files will be saved (D:\Python in this case).
  • fname constructs the filename format by combining timestr and the switch IP address for each iteration.
  1. Username and Password:
  • The script defines a username ("cisco") but prompts the user to enter the password securely using getpass.getpass("Enter Password:").
  1. Processing Switches from a File:
  • The script opens a file named "myswitches.txt" containing a list of switch IP addresses (one per line).
  • It iterates through each line in the file using a for loop.
  • For each line:
    • ip_address variable stores the current switch IP address after removing leading/trailing whitespaces using strip().
    • The check_switch function is called to verify if the switch is reachable.
    • If the switch is unreachable, a message is printed, and the script moves on to the next IP address in the file.
  1. Connecting to the Switch:
  • If the switch is reachable, the script creates an SSH client object using paramiko.SSHClient().
  • It sets the missing host key policy to paramiko.AutoAddPolicy(). This is NOT recommended for production environments as it automatically accepts unknown host keys. In production, you should manage known host keys securely.
  • The script connects to the switch using ssh_client.connect(hostname=ip_address, username=username, password=password).
  • Upon successful connection, a message is printed.
  1. Sending Commands and Collecting Output:
  • The script creates a shell channel using ssh_client.invoke_shell().
  • It sends various Cisco IOS commands one by one using remote_connection.send():
    • terminal length 0: Disables pagination for command output.
    • show running-config: Retrieves the running configuration.
    • show interfaces description: Shows interface descriptions.
    • show interfaces status: Shows interface statuses.
    • show vlan brief: Shows a brief overview of VLANs.
    • show inventory: Displays hardware inventory information.
    • show version: Shows the switch version information.
    • exit: Exits the terminal session.
  • A brief delay (time.sleep(10)) is added to allow the device to respond to the commands.
  • The script then receives the command output using remote_connection.recv(655350). This receives a maximum of 655350 bytes of data. You might need to adjust this value based on the expected output size.
  1. Saving Output to a File:
  • The script constructs the filename for the current switch using f"{fname}_{ip_address}.txt.
  • It opens the file in binary write mode ("wb") using open().
  • The received command output is written to the file using saveoutput.write(readoutput).
  • A success message is printed upon successful file saving.
  • The file is closed using saveoutput.close().
  1. Closing the Connection:
  • Finally, the script closes the SSH client connection using ssh_client.close().
  1. Exception Handling:
  • The try...except block ensures the script continues execution even if an error occurs while connecting to a switch

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.

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.