Python for Network Automation

Why Python for Network Engineering?

In the dynamic field of network engineering, efficiency, accuracy, and speed are paramount. With the growing complexity of network systems, the need for automation is more evident than ever. Python, a versatile and user-friendly programming language, has become a popular tool for network automation. This blog post will provide a step-by-step guide on how Python can be used to automate various network engineering tasks.

Python is a high-level, interpreted programming language that is known for its simplicity and readability. It has a rich set of libraries that can help automate network tasks, making it a preferred choice for network engineers. Libraries like Netmiko, NAPALM, and Paramiko allow network engineers to interact with network devices, automate configuration tasks, and retrieve network information.
 

Step 1: Setting Up Your Python Environment

Before you can start automating network tasks with Python, you need to set up your Python environment. This involves installing Python and the necessary libraries. Here's how you can do it:

1. Download and install Python from the [official Python website](https://www.python.org/).

2. Install the necessary libraries using pip, Python's package installer. You can do this by running the following command in your command prompt or terminal:
pip install netmiko napalm paramiko

Step 2: Automating Network Configuration with Netmiko

What is Netmiko?

Netmiko is an open-source Python library that simplifies the process of automating and managing network devices. Built on top of another Python library called Paramiko, Netmiko extends Paramiko's capabilities to interact with network devices over SSH. It supports a wide range of devices from many vendors, including Cisco, Juniper, Arista, and more.

How Does Netmiko Work?

Netmiko works by establishing a secure SSH connection to the network device. Once the connection is established, Netmiko can send commands to the device and retrieve the output. This allows for remote configuration and automation of network devices.

Here's a simple diagram illustrating the process:


Here's a step-by-step guide on how you can use Netmiko to automate the configuration of a network device:

1. Import the necessary library:
from netmiko import ConnectHandler​​​​​​​

2. Define your device parameters:
 device = {
    
'device_type': 'cisco_ios',
    '
ip':   '10.0.0.1',
    '
username': 'admin',
    '
password': 'password',
}

NOTE: I am taking Cisco device as an example to connect from my server using Python

3. Establish a connection to the device:
connection = ConnectHandler(**device)​​​​​​​

4. Define your configuration commands:
config_commands = [
    '
interface GigabitEthernet0/1',
    '
ip address 192.168.1.1 255.255.255.0',
    '
no shutdown'
]

5. Send the configuration commands to the device:
output = connection.send_config_set(config_commands)

6. Retrieve the configuration
config = connection.send_command('show running-config')

7. Print the configuration
print(config) 

Netmiko handles the low-level details of interacting with the device, allowing network engineers to focus on higher-level tasks. It's a powerful tool for any network engineer working with Python.

In this script:

1. We first import the necessary library (Netmiko).

2. We define our device parameters, including the device type, IP address, username, and password.

3. We establish a connection to the device using the `ConnectHandler` function from Netmiko, passing in our device parameters.

4. We define a list of configuration commands that we want to send to the device.

5. We send the configuration commands to the device using the `send_config_set` method of our connection object.

6. We retrieve the current running configuration using the `send_command` method with the 'show running-config' command.

7. We print the retrieved configuration.

Step 3: Automating Network Configuration with Paramiko

What is Paramiko?

Paramiko is a Python implementation of the SSHv2 protocol. It provides a secure, encrypted channel to remotely connect to devices and execute commands. Paramiko is often used as a low-level building block for more complex network automation tasks.

Here's an example of a Python script using Paramiko to connect to a device and execute a command:

import paramiko

# Create an SSH client
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

# Connect to the device
ssh.connect('10.0.0.1', username='admin', password='password')

# Execute a command
stdin, stdout, stderr = ssh.exec_command('show ip interface brief')

# Print the output
print(stdout.read().decode())

# Close the connection
ssh.close()

This script establishes an SSH connection to a device, executes the command 'show ip interface brief', and prints the output.

Step 4: Paramiko vs Netmiko: A Comparison

While Paramiko and Netmiko are both used for network automation, they serve different purposes and offer different levels of abstraction.

1. Level of Abstraction: Paramiko provides a low-level, granular interface for managing SSH connections. It offers more control but requires more code to handle common tasks. Netmiko, on the other hand, provides higher-level abstractions that simplify common network automation tasks.

2. Multi-vendor Support: Paramiko can connect to any device that supports SSH, but it doesn't provide any special handling for different types of devices. Netmiko supports a wide range of devices from many vendors and includes features to handle the quirks and peculiarities of different devices.

3. Handling Prompts: When you connect to a device with Paramiko, you need to handle prompts for usernames, passwords, and other input manually. Netmiko automatically handles these prompts, making your scripts simpler and more robust.

While Paramiko offers more control and flexibility, Netmiko simplifies many common network automation tasks, making it a popular choice for network engineers. The choice between Paramiko and Netmiko will depend on your specific needs and the complexity of the tasks you're trying to automate.

Step 5: Advanced Network Automation with Paramiko and Netmiko

While the above examples demonstrate basic usage of Paramiko and Netmiko, both libraries can be used for more complex network automation tasks. For example, you could use Paramiko or Netmiko to automate the configuration of multiple devices, handle errors and exceptions, log activity, and more.

Here's an example of a more advanced script using Netmiko to configure multiple devices:

from netmiko import ConnectHandler
from
getpass import getpass

# Define the device parameters
devices = [
    {
        'device_type': '
cisco_ios',
        'ip':   '
10.0.0.1',
        'username': '
admin',
        'password':
getpass(),
    },
    {
        'device_type': '
cisco_ios',
        'ip':   '
10.0.0.2',
        'username': '
admin',
        'password':
getpass(),
    },

    # Add more devices as needed
]

# Define the configuration commands
commands = [
    'i
nterface GigabitEthernet0/1',
    '
ip address 192.168.1.1 255.255.255.0',
    '
no shutdown',
]

# Function to configure a device
def configure_device(device, commands):

    # Establish a connection to the device
    connection = ConnectHandler(**device)

    # Send the configuration commands
    output = connection.send_config_set(commands)

    # Print the output
    print(output)

# Disconnect from the device
    connection.disconnect()

# Configure each device
for device in devices:
    configure_device(device, commands)

This script prompts for a password using the `getpass` function, connects to each device in the `devices` list, sends the configuration commands, and then disconnects. This is just one example of how you can use Paramiko and Netmiko for advanced network automation tasks.

Conclusion:

In conclusion, Python, with its powerful libraries like Paramiko and Netmiko, offers network engineers a versatile toolset for automating and managing network devices. Whether you're just starting your journey in network automation or you're a seasoned professional, Python has something to offer you.

Happy coding!