Python package – “netmiko”

It’s a very important package used for Network Automation. This is quite similar to “paramiko” and used for SSH connection and executing cetain commands to a Variety of Network Devices.

Another advantage of “netmiko” is that it works with variety of vendors. Some of the common and mostly used supported platform types and their abbreviations to be called in Netmiko are as follows. Depending upon the selection of the platform type, Netmiko can understand the returned prompt and the correct way to SSH into the specific device. 

arista_eos: AristaSSH,
aruba_os: ArubaSSH,
avaya_ers: AvayaErsSSH,
avaya_vsp: AvayaVspSSH,
checkpoint_gaia: CheckPointGaiaSSH,
cisco_asa: CiscoAsaSSH,
cisco_ios: CiscoIosBase,
cisco_nxos: CiscoNxosSSH,
cisco_wlc: CiscoWlcSSH,
cisco_xe: CiscoIosBase,
cisco_xr: CiscoXrSSH,
f5_ltm: F5LtmSSH,
fortinet: FortinetSSH,
juniper: JuniperSSH,
juniper_junos: JuniperSSH,
linux: LinuxSSH,
mellanox_ssh: MellanoxSSH,
paloalto_panos: PaloAltoPanosSSH,

Here’s an example of a simple script to log in to the router and show the “show ip int brief” output:

from netmiko import ConnectHandler

# Define a connection Handler i.e. Device dictionary
CISCO_3850 = {
    'device_type': 'cisco_xe',
    'ip': '192.168.1.1',
    'username': 'mrcissp',
    'password': 'networkautomation',
    'port': '22',          # optional, defaults to 22
    'secret': '', # optional, defaults to ''
}
# Establish an SSH connection to the device by passing in the device dictionary.
CONNECT = ConnectHandler(**CISCO_3850)

# Execute show commands.
OUTPUT = CONNECT.send_command('show ip int brief')
print(OUTPUT)

# Cleanly disconnecting the connection 
CONNECT.disconnect()

Let’s take another example where we will make some changes to the running configuration to a network device i.e. in our case is router.

Refer to below program if we need to change/add the description of GigabitEthernet 0/0/0 router interface.

# Execute Configuration commands.
OUTPUT = CONNECT.send_command('show run int gi0/0/0')
print(OUTPUT)

CONFIG_COMMAND_SET = ['int gi0/0/0', 'description PRODUCTION']
OUTPUT = CONNECT.send_config_set(CONFIG_COMMAND_SET)
print(OUTPUT)

OUTPUT = CONNECT.send_command('show run int gi0/0/0')
print(OUTPUT)
$ python demo_netmiko.py
Building configuration...

Current configuration : 99 bytes
!
interface GigabitEthernet0/0/0
 description PROD
 no ip address
 shutdown
 negotiation auto
end

config term
Enter configuration commands, one per line.  End with CNTL/Z.
Router(config)#int GigabitEthernet0/0/0
Router(config-if)#description TEST
Router(config-if)#end
Router#
Building configuration...

Current configuration : 99 bytes
!
interface GigabitEthernet0/0/0
 description TEST
 no ip address
 shutdown
 negotiation auto
end

As we can see, for config push, we do not have to perform any additional configurations but just specify the commands in the same order as we send them manually to the router in a list, and pass that list as an argument to the send_config_set function. The output in Before config push is a simple output of the g0/0/0 interface, but the output under After config push now has the description that we configured using the list of commands.

Exception handling in “netmiko”

When we design our Python script, we assume that the device is up and running and also that the user has provided the correct credentials, which is not always the case. Sometimes there’s a network connectivity issue between Python and the remote device or the user enters the wrong credentials. Usually, python will throw an exception if this happens and will exit, which is not the optimum solution.

In this section, we will demonstrate how to handle the different exception with “netmiko”. The first one is “AuthenticationException”, and will catch the authentication errors in the remote device. The second class is “NetMikoTimeoutException”, which will catch timeouts or any connectivity. Refer to below program

from netmiko import ConnectHandler
from netmiko.ssh_exception import NetMikoTimeoutException
from netmiko.ssh_exception import NetMikoAuthenticationException

# Handling exception
try:
    CONNECT = ConnectHandler(**CISCO_3850)
except NetMikoTimeoutException:
    print('Failed to connect to ' + CISCO_3850['ip'] + ' due to connection issue' + '- Verify Network connectivity')
except NetMikoAuthenticationException:
    print('Failed to connect to ' + CISCO_3850['ip'] + ' due to Wrong Credential' + '- Verify them')
else:
    CONNECT.disconnect()

Let’s execute this for two cases

  1. A dummy IP
  2. Wrong Credentials
$python demo_netmiko.py
 Failed to connect to 10.24.7.4 due to connection issue- Verify Network connectivity
$python demo_netmiko.py
Failed to connect to 10.24.7.3 due to Wrong Credential- Verify them

There is another important method find_prompt() which is used to find the current prompt of the executed commands.

# Finding the current prompt i.e. enable prompt
CONNECT = ConnectHandler(**CISCO_3850)
PROMPT = CONNECT.find_prompt()
print('Our current prompt is ' + PROMPT)
$python demo_netmiko.py
Our current prompt is Router#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.