Python: Getting JSON data from remote NX-OS device

5 hours ago

In this quick guide I am going to show you how to reach remote Cisco Nexus 9k (sandbox) and get some JSON data using Python. JSON stands for JavaScript Object Notation and it is basically a syntax for storing and exchanging data. Python has a built-in package called json, which can be used to work with JSON data. You can import JSON modul to Python script as follow:

import json

For our script we will also need Netmiko module. It is Python implementation of the SSHv2 protocol providing both client and server functionality. As this is not built-in module, you need to install it. Easiest way to install Netmiko is using PIP:

pip install netmiko

Once Netmiko is installed you can import it to the script simlarly as JSON:

import netmiko

However we will use only ConnectHandler function so we can import it as follow:

from netmiko import ConnectHandler as CH

Now, when we have all modules imported, let's connect to the device. Anyone can access the "Open NX-OS Programmability" Always On Sandbox directly using the following information:

  • Nexus 9000v Host: sbx-nxos-mgmt.cisco.com
  • SSH Port: 8181
  • Username: admin
  • Password: Admin_1234!

First, we need to create dictionary based on Netmiko documentation:

remote_NXOS = {
    'device_type': 'cisco_ios',
    'ip': 'sbx-nxos-mgmt.cisco.com',
    'username': 'admin',
    'password': 'Admin_1234!',
    'port': 8181
}

It looks like JSON data, right? Yes, but JSON uses double quotes. Then, we need to establish an SSH connection to the device by passing in the device dictionary:

connect = CH(**remote_NXOS)

Once we are successfully authenticated we can send some Cisco IOS command to remote device:

outShVer = json.loads(connect.send_command('show version | json'))

json.loads() method allows us to parse a JSON string to Python and output is stored in variable called outShVer.

We will do the same with command 'show ip int brief | json'. The output of this command will be JSON string containing information about configured interfaces including Interface name, VRF name, IP address, states etc.

json_out = json.loads(connect.send_command('show ip int brief | json'))

As we want to get only Name, IP address and States for each interface we need to use FOR loop:

for interface in json_out["TABLE_intf"]["ROW_intf"]:
    print('INTERFACE :', interface["intf-name"])
    print('IP ADDRESS:', interface["prefix"])
    print('LINK STATE:', interface["proto-state"] + '/' + interface["link-state"] + '\n')

The purpose of this script is to demonstrate how to connect remote network device and get some data. The script is not perfect. Password can be asked from user, connection can be handled with exceptions and many more. Feel free to use it and improve it however you like. Try to get also other infromation from other IOS commands.

I hope this article is benefical for you. Good luck with your studies.