Python: Network Automation with Netmiko

1 minute read

Updated:

What is Netmiko?

Netmiko is a multi-vendor library to simplify Paramiko SSH connections to network devices. Netmiko supports a wide range of devices. These devices fall into three categories, see supported platforms on Github.

Library Purpose

Netmiko simplifies SSH management to network devices. The purposes of this library are the following:

  • Successfully establish an SSH connection to the device.
  • Simplify the execution, retrieval, and formatting of show commands.
  • Simplify the execution of configuration commands.
  • Provide a (relatively) uniform API for interacting with devices.

To install netmiko simply use pip for installation.

pip install netmiko

Netmiko has the following requirements (which pip will install for you)

  • Paramiko >= 2.4.3
  • scp >= 0.13.2
  • pyserial
  • textfsm

We will use our previous topology as below:

picture

Lab Configuration same as previous.

Getting Started

Import “ConnectHandler” from the Netmiko library.

Switch

from netmiko import ConnectHandler

# Create a dictionary for a particular device
S1 = {
 'device_type': 'cisco_ios',
 'ip': '192.168.10.10',
 'username': 'admin',
 'password': 'cisco',
 'secret' : 'cisco',
}

'''calling the ConnectHandler Library [**S1] means telling
python to consider the contents of the dictionary as key value pairs
instead of single elements.'''

net_connect = ConnectHandler(**S1)
net_connect.enable()  # device enable mode

# Sending a command in to the switch --->
output = net_connect.send_command("show ip int br")
print(output)

Router

# Config_commands sample
from netmiko import ConnectHandler

R1 = {
    'ip':   '192.168.10.11',
    'username': 'admin',
    'password': 'cisco',
    'secret' : 'cisco',
    'device_type': 'cisco_ios',
}

net_connect = ConnectHandler(**R1)
net_connect.enable()  # device enable mode

#Execute configuration change commands 
#(will automatically enter into config mode)
config_commands = [ 'int lo0',
                    'ip add 1.1.1.1 255.255.255.255',
                    'no shut' ]
output = net_connect.send_config_set(config_commands)
print(output)

Sending commands

Netmiko has several ways to send commands:

  • send_command - send one command
  • send_config_set - send list of commands or command in configuration mode
  • send_config_from_file - send commands from the file (uses send_config_set method inside)
  • send_command_timing - send command and wait for the output based on timer

Netmiko and TextFSM

In Netmiko 2.0.0 (December 2017), added support for direct TextFSM integration particularly for ntc-templates.

Simply stated, it allows you to take unstructured data and convert it to structured data. Or worded differently, it takes a block of text and converts it to lists and dictionaries (or some combination thereof). See more about TextFSM here.

Example of Netmiko

More script at GitHub

Comments