simplifying network automation in Python

Paramiko, designed for network engineers. It simplifies working with SSH connections and adds a number of methods and interfaces for interacting with network devices.

This module supports a wide range of network devices – from Cisco and Juniper to Arista and HP. All you need to do is define the device parameters as a dictionary, and Netmiko will take care of the rest.

Let's install:

pip install netmiko

Connecting to devices

First, we set the device parameters in the form of a dictionary. These parameters include the device type, IP address, login, password and, if necessary, a secret password for enable mode. Example dictionary for connecting to a Cisco router:

from netmiko import ConnectHandler

cisco_router = {
    'device_type': 'cisco_ios',
    'host': '192.168.1.1',
    'username': 'user',
    'password': 'password',
    'secret': 'enable_secret',
    'port': 22,  # по дефолту порт 22
}

Netmiko uses the object ConnectHandler to create an SSH connection with network devices. This object automatically selects the required class to work with the device based on the specified parameters.

net_connect = ConnectHandler(**cisco_router)

After creating the object ConnectHandler You can use various methods to interact with the device.

Many devices require switching to the privileged enable mode to execute configuration commands. For this purpose the method is used enable()which automatically enters the command to switch to enable mode and enters the required password:

net_connect.enable()

To exit enable mode, use the method exit_enable_mode():

net_connect.exit_enable_mode()

Sending commands and configurations to Netmiko

Method send_command used to send single commands to a device and receive their output. The method is good for executing show commands and other one-time commands:

from netmiko import ConnectHandler

# определение параметров устройства
cisco_router = {
    'device_type': 'cisco_ios',
    'host': '192.168.1.1',
    'username': 'user',
    'password': 'password',
    'secret': 'enable_secret',
    'port': 22,
}

# создание соединения
net_connect = ConnectHandler(**cisco_router)

# выполнение команды и получение результата
output = net_connect.send_command('show ip int brief')
print(output)

# зкрытие соединения
net_connect.disconnect()

Method send_command has a couple of parameters that can be used to customize the execution of the command:

  • command_string: command string to execute.

  • expect_string: line up to which to wait for output (if not specified, the prompt string is used).

  • delay_factor: Delay multiplier before starting to search for a string.

  • max_loops: Maximum number of iterations before throwing an error (default 500).

Method send_config_set used to send one or more configuration commands. It allows you to make device configuration changes:

# определение конфигурационных команд
config_commands = [
    'interface Loopback0',
    'ip address 10.0.0.1 255.255.255.0',
]

# отправка конфигурационных команд
output = net_connect.send_config_set(config_commands)
print(output)

Method send_config_set can accept a list of commands or a single command as a string. It also automatically switches to the conf. mode and exits it after executing commands.

Method send_config_from_file allows you to load configuration commands from a file. This way you can use prepared configuration scripts in advance:

# отправка конфигурационных команд из файла
output = net_connect.send_config_from_file('config.txt')
print(output)

File config.txt should contain a list of configuration commands, each command on a new line.

Besides the above methods, Netmiko has other good methods:

  1. Method send_command_timing:

    • Similar send_command, but is based on timing. Good when the command output may change over time and more control over waiting for output is needed.

      output = net_connect.send_command_timing('show version')
      print(output)
  2. Method save_config:

    • Allows you to save the current configuration on the device (we have already looked at it in the examples above, but it’s worth mentioning here):

      output = net_connect.save_config()
      print(output)
  3. Method cleanup:

Examples of scripts with Netmiko

Bulk configuration update on routers

In large operations, it is often necessary to update configurations on many routers at the same time. With Netmiko you can automate this process:

from netmiko import ConnectHandler
import logging

# включение логирования
logging.basicConfig(filename="netmiko_global.log", level=logging.DEBUG)
logger = logging.getLogger("netmiko")

# определение устройств
devices = [
    {
        'device_type': 'cisco_ios',
        'host': '192.168.1.1',
        'username': 'admin',
        'password': 'password',
        'secret': 'secret',
    },
    {
        'device_type': 'cisco_ios',
        'host': '192.168.1.2',
        'username': 'admin',
        'password': 'password',
        'secret': 'secret',
    },
]

# команды для обновления конфигурации
config_commands = [
    'interface GigabitEthernet0/1',
    'description Uplink to Core',
    'ip address 10.0.0.1 255.255.255.0',
]

# выполнение обновления конфигурации на всех устройствах
for device in devices:
    net_connect = ConnectHandler(**device)
    net_connect.enable()
    output = net_connect.send_config_set(config_commands)
    print(output)
    net_connect.disconnect()

The script connects to each router, goes into enable mode, sends configuration commands and displays the result.

Collecting interface status data

The script collects data on the state of interfaces from several switches and saves it to a file for later analysis:

from netmiko import ConnectHandler
import csv

# определение устройств
devices = [
    {
        'device_type': 'cisco_ios',
        'host': '192.168.1.10',
        'username': 'admin',
        'password': 'password',
        'secret': 'secret',
    },
    {
        'device_type': 'cisco_ios',
        'host': '192.168.1.11',
        'username': 'admin',
        'password': 'password',
        'secret': 'secret',
    },
]

# файл для сохранения данных
output_file="interface_status.csv"

# открытие файла для записи
with open(output_file, mode="w", newline="") as file:
    writer = csv.writer(file)
    writer.writerow(['Device', 'Interface', 'Status', 'Protocol'])

    for device in devices:
        net_connect = ConnectHandler(**device)
        net_connect.enable()
        output = net_connect.send_command('show ip int brief')
        
        for line in output.splitlines()[1:]:
            if line:
                parts = line.split()
                writer.writerow([device['host'], parts[0], parts[4], parts[5]])
        
        net_connect.disconnect()

The script connects to each switch and executes the command show ip int briefretrieves interface state data and writes it to a CSV file.

Automatic backup of configurations

Regular backups of network device configurations are done to ensure network reliability.

The script automates the process of creating configuration backups:

from netmiko import ConnectHandler
import datetime

# определение устройств
devices = [
    {
        'device_type': 'cisco_ios',
        'host': '192.168.1.1',
        'username': 'admin',
        'password': 'password',
        'secret': 'secret',
    },
    {
        'device_type': 'cisco_ios',
        'host': '192.168.1.2',
        'username': 'admin',
        'password': 'password',
        'secret': 'secret',
    },
]

# текущая дата для имени файла
current_date = datetime.datetime.now().strftime("%Y-%m-%d")

for device in devices:
    net_connect = ConnectHandler(**device)
    net_connect.enable()
    hostname = net_connect.find_prompt().strip('#')
    config_output = net_connect.send_command('show running-config')
    
    # сохранение конфигурации в файл
    with open(f'{hostname}_backup_{current_date}.txt', 'w') as file:
        file.write(config_output)
    
    net_connect.disconnect()

The script connects to each device, retrieves the current configuration using the command show running-config and saves it to a file, using the device name and the current date to name the file.


Want to learn more about Python and other programming languages? In the OTUS course catalog you will find current courses from current market experts in any direction. Go to the catalog and see for yourself.

Similar Posts

Leave a Reply

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