Automate Cisco Devices Using Python Netmiko

May 23, 2024
12 min read

Aarini Patil

Table of Contents

Quick navigation7 sections

Welcome to the exciting world of network automation using Python and Netmiko! Are you tired of repetitive network configuration tasks? Python, combined with the powerful Netmiko library, can revolutionize how you manage Cisco routers and switches. In this comprehensive guide, we'll dive into how you can use Python scripts to automate your network operations, making them more efficient, error-free, and scalable.

Why Use Python and Netmiko for Network Automation?

Before we jump into the coding part, let's understand why Python and Netmiko are preferred for automating Cisco devices. Python is known for its simplicity and readability, making it perfect for scripting and automation. Netmiko, developed by Kirk Byers, is an open-source Python library designed specifically for simplifying SSH connections to routers and switches. It supports a wide range of devices from Cisco and other vendors, making it an indispensable tool in any network administrator’s toolkit.

Using Python and Netmiko, you can perform tasks like configuration updates, routine backups, and multi-device command deployment without manual intervention. This not only saves time but also reduces the likelihood of human error, ensuring more reliable network operations.

Are you ready to streamline your network tasks? Let’s look at how you can start using Python with Netmiko to automate your Cisco devices effortlessly.

Setting Up Your Environment

First things first, setting up your Python environment with Netmiko is straightforward. You'll need to have Python installed on your computer along with pip, Python’s package installer. Here’s how you can get started:

  • Install Python: Ensure Python (version 3.6 or higher) is installed. You can download it from the official Python website.
  • Install Netmiko: Once Python and pip are set up, you can install Netmiko using pip. Simply run pip install netmiko in your command-line interface.
  • Prepare Your Devices: Ensure that the Cisco devices you intend to manage are accessible via SSH, as Netmiko uses SSH for connections.

With your environment ready, you are now set to create some automation magic!

Basic Concepts of Netmiko

Understanding a few fundamental concepts of Netmiko can help you utilize this tool more effectively. Let's break down these basics:

  • Connection Handler: The core component of Netmiko is the ConnectHandler class. This class manages the SSH connection to your device, abstracting many of the complexities involved in these connections.
  • Device Type: When you establish a connection, you need to specify the type of device you're connecting to. This helps Netmiko understand how to interact with the device, considering each vendor's peculiarities.
  • Commands Execution: Executing commands is straightforward—once connected, use the send_command() method to execute commands and retrieve outputs.

Basic Script to Connect to a Cisco Router

Let’s start with a basic script to connect to a Cisco router. This will be our foundation for more complex automation tasks. Here's a simple script to start:

import netmiko

connection = netmiko.ConnectHandler(
device_type='cisco_ios',
ip='your_router_ip',
username='your_username',
password='your_password'
)

print(connection.send_command('show version'))
connection.disconnect()

This script connects to your Cisco device, executes the show version command to retrieve hardware and software information, and then disconnects. It’s a simple yet powerful example of how you can use Python and Netmiko to communicate with network devices.

Interested in diving deeper into the capabilities of Netmiko? Check out this comprehensive guide on Netmiko's main concepts.

Expanding Your Scripts

Now that you’ve established a basic connection to a device, it’s time to expand your script to handle multiple devices and perform various tasks. What could we automate next? How about updating device configurations or performing routine backups? The possibilities are endless!

Automating Configuration Changes

One of the most common tasks in network management is updating device configurations. Using Python and Netmiko, you can automate this process across multiple devices, which is a significant time-saver. Here’s a step-by-step guide on how you can automate configuration changes:

  1. Prepare Your Configuration File: Start by creating a text file that contains all the configuration commands you want to apply. Name it config_updates.txt. This file might include commands to change passwords, update access lists, or modify interface settings.
  2. Write the Python Script: Below is a Python script that reads commands from your configuration file and applies them to the list of devices specified.
import netmiko

def update_device_config(device, config_file):
try:
connection = netmiko.ConnectHandler(**device)
connection.enable() # Entering privilege mode
print(f"Connected to {device['ip']}")
output = connection.send_config_from_file(config_file)
print(output) # Print the output from the configuration update
connection.save_config()
connection.disconnect()
print(f"Configuration updated and saved for {device['ip']}")
except netmiko.NetMikoTimeoutException:
print("Failed to connect to device", device['ip'])

# List of devices to be updated
devices = [
{'device_type': 'cisco_ios', 'ip': '192.168.1.1', 'username': 'admin', 'password': 'admin123'},
{'device_type': 'cisco_ios', 'ip': '192.168.1.2', 'username': 'admin', 'password': 'admin123'},
# add more devices if necessary
]

config_file = "config_updates.txt"

for device in devices:
update_device_config(device, config_file)

This script demonstrates how you can loop through a list of devices, apply configuration updates from a file, and save these configurations. This approach is highly scalable, reducing the risk of errors that often occur with manual configurations.

Performing Routine Backups

Another essential task for network administrators is performing routine backups of device configurations. This ensures that you have recoverable data in the event of device failure or other issues. Here’s how to automate backups using Python and Netmiko:

import os
import datetime
import netmiko

backup_folder = 'config_backups'
os.makedirs(backup_folder, exist_ok=True)

def backup_config(device):
connection = netmiko.ConnectHandler(**device)
connection.enable()
config_data = connection.send_command('show running-config')
today = datetime.datetime.now().strftime('%Y-%m-%d')
filename = f"{backup_folder}/config_{device['ip']}_{today}.txt"
with open(filename, 'w') as file:
file.write(config_data)
print(f"Backup of {device['ip']} completed successfully.")
connection.disconnect()

# List of devices to backup
devices = [
{'device_type': 'cisco_ios', 'ip': '192.168.1.1', 'username': 'admin', 'password': 'admin123'},
{'device_type': 'cisco_ios', 'ip': '192.168.1.2', 'username': 'admin', 'password': 'admin123'},
# add more devices if necessary
]

for device in devices:
backup_config(device)

This script not only automates the data retrieval process but also organizes it by date, making it much easier to manage backups over time. Automating these backups can significantly reduce the workload on network teams and help in maintaining consistent data integrity and availability.

Error Handling and Logging

As scenarios grow more complex, dealing with errors becomes crucial. Whether it’s handling authentication failures, timeout errors, or unexpected command outputs, Netmiko allows for robust error handling mechanisms. You can use Python’s try/except blocks to catch and respond to exceptions appropriately. Additionally, implementing logging will help in maintaining records of what commands were sent to which devices and their outputs, aiding in troubleshooting and documentation:

import logging
from netmiko import ConnectHandler

# Configuring logging
logging.basicConfig(filename='netmiko_log.txt', level=logging.DEBUG)
logger = logging.getLogger("Netmiko")

# Example device
device = {
'device_type': 'cisco_ios',
'host': '10.0.1.1',
'username': 'admin',
'password': 'admin',
'secret': 'secret'
}

try:
net_connect = ConnectHandler(**device)
output = net_connect.send_command('show version')
print(output)
net_connect.disconnect()
except Exception as e:
logger.error(f"Failed to connect to {device['host']}: {e}")

This script includes basic logging and exception handling, which will guide you in managing automation scripts more professionally.

Integrating Netmiko into Larger Automation Frameworks

While Netmiko is powerful on its own, integrating it into larger frameworks like Ansible, SaltStack, or even custom-built Python applications enhances its functionality. This allows for scheduling, orchestration, and comprehensive policy-driven network automation.

For instance, Ansible, an open-source tool, is crafted for IT orchestration. When Netmiko is used as a module in Ansible, it enables network modules to communicate with a wide range of devices across different platforms, thereby facilitating broad and controlled automation across network infrastructures.

Incorporating Netmiko in such frameworks demands a deeper understanding of both networking concepts and automation methodologies, but the scalability and resilience it adds to network operations are worth the investment.

Conclusion

By leveraging Python and the Netmiko library, network administrators can automate a wide array of tasks that typically consume a considerable amount of time and are prone to manual errors. From connecting to a Cisco router, applying bulk configuration changes, to backing up configurations, automation not only increases efficiency but also enhances the consistency and reliability of network operations.

Automating your Cisco device operations with Python and Netmiko is not only about simplifying repetitive tasks; it's about transforming the way networks are managed and maintained. As networks grow in complexity and size, the ability to swiftly and reliably push changes or perform routine backups becomes invaluable. We encourage you to expand on these scripts, tailor them to your specific needs, and explore further possibilities to maximize the efficiency of your network management.

Embrace network automation today and see how it can revolutionize your workflow, reduce operational costs, and improve the overall reliability of your network. Happy automating!

Related Courses

Enhance your knowledge with these recommended courses

Network Automation with Python Netmiko

Network Automation with Python Netmiko

A great explanation of Python Netmiko Library

Become an Instructor

Share your knowledge and expertise. Join our community of instructors and help others learn.

Apply Now
Aarini Patil

About the Author

Aarini Patil

Hi this is Aarini. I'm a network expert who works 12 years as a Network Security manager. I'm going to teach everything you need to know with my blogs.

Share this Article

Related Articles

Network AutomationSeptember 14, 2024

In-Depth Analysis: DEVCOR 350-901 Exam Topics and Domains

In-Depth Analysis: DEVCOR 350-901 Exam Topics and Domains In-Depth Analysis: DEVCOR 350-901 Exam Topics and Domains As the world of networking expands and diversifies, the need for skilled developers and...

Read Article
Network AutomationSeptember 14, 2024

Preparing for DEVCOR 350-901: Top Study Resources and Strategies

Preparing for DEVCOR 350-901: Top Study Resources and Strategies Conquering the DEVCOR 350-901 Exam: A Strategic Guide If you're geared up to tackle the DEVCOR 350-901, you know it's no...

Read Article
Network AutomationSeptember 14, 2024

Network Automation Certifications: Which One is Right for You?

Network Automation Certifications: Which One is Right for You? Exploring Network Automation Certifications: A Guide to Elevating Your IT Career Are you considering elevating your IT career with a network...

Read Article
Network AutomationAugust 14, 2024

Integrating pyATS with CI/CD Pipelines: A Reference Guide

Integrating pyATS with CI/CD Pipelines: A Reference Guide The world of software development and testing is perpetually evolving, requiring new methodologies and tools to enhance efficiency and reliability. One such...

Read Article
Network AutomationAugust 14, 2024

Introduction to pyATS: The Ultimate Python Testing Framework

Introduction to pyATS: The Ultimate Python Testing Framework Introduction to pyATS: The Ultimate Python Testing Framework Welcome to the world of pyATS, where network testing is transformed into a smooth,...

Read Article
Network AutomationAugust 14, 2024

pyATS vs. Robot Framework: Which Testing Tool Wins?

pyATS vs. Robot Framework: Which Testing Tool Wins? pyATS vs. Robot Framework: Which Testing Tool Wins? Choosing the right Python test automation tool can significantly influence the efficiency and...

Read Article

Subscribe for Exclusive Deals & Promotions

Stay informed about special discounts, limited-time offers, and promotional campaigns. Be the first to know when we launch new deals!