Python Netmiko – network automation

If you have been using expect on Linux or paramiko with python, then you will feel the ease of programing with netmiko. Netmiko really simplifies ssh session management on network devices. To install netmiko use pip3 or pip installer


pip3 install netmiko
Collecting netmiko
  Downloading https://files.pythonhosted.org/packages/0d/18/abb1f084cffc5d085e433a56cd7cebca02e2d0ce773f3d5185ae140e4cfd/netmiko-2.4.1-py2.py3-none-any.whl (142kB)
     |████████████████████████████████| 143kB 520kB/s

Netmiko currently supports many network operating systems, including Cisco IOS variants, JunOS, Linux etc. You can see complete list at netmiko page. Main advantage of netmiko over paramiko is you can easily issue multiple commands over same ssh session.

Here is quick sample code to list files on a remote Linux machine.


#!/usr/local/bin/python3
from netmiko import ConnectHandler

device = {
    'device_type': 'linux',
    'host': '192.168.0.25',
    'username': 'guest',
    'password': 'xxxxxx',
}

try:
     net_connect = ConnectHandler(**device)
except Exception:
     print("SSH failed on", hostname)
     sys.exit()

try:
     listfiles = net_connect.send_command("ls -l /etc")
     print(listfiles)
except:
     print("Command failed")

Save it as test.py and execute to see list of files in /etc on remote Linux host.


./test.py
total 4120
-rw-r--r--.  1 root root        44 May 20  2016 adjtime
-rw-r--r--.  1 root root      1512 Jan 12  2010 aliases
-rw-r--r--.  1 root root     12288 Apr  3  2013 aliases.db
drwxr-xr-x.  2 root root      4096 Apr  3  2013 alsa