snake on branch

A few days ago I stumbled upon the python interpreter on the Nexus platform. It got me to tinkering.

In the past, I have had a requirement to grab a list of all of the interfaces on a box, the IP’s, and the masks. The interfaces and IP’s can easily be obtained from a show ip int br, and using column select to grab the relevant columns (hold down Alt when you are selecting in putty, if you didn’t know that before then go try it!). Getting the subnet masks for those is a little less trivial though.

As a side note, in the past I’ve used this:

sh ip int | i is up|Internet add

This works, but you have to mess a little to strip out just the bits you want (not a lot of work with a decent text editor though, I admit).

Anyway, more just to see if I could, I wrote a python script to extract the structured dictionary response from a “show ip interface” and parse out the relevant pieces and print them into a fixed width table, under the columns ‘Name’,’IP’,’CIDR’,’Mask’,’Admin’,’Link’,’Protocol’.

If you drop the script into bootflash:scripts/, then type “source ?” into the CLI, you’ll see that it’s available as a command. You can even set up a command alias so that you can access it quicker.

I’ve put the code on gitlab at: https://gitlab.com/geekynick/nexus-python

And here it is too:

#!/usr/bin/env python
import sys, re

# color escape sequences

def nxos_help_string(args):
    # display online help (if asked for) for NX-OS' "source" command 
    # either in config mode or at the exec prompt, if users type "source <script> ?" then help_string appears
    # CREDIT: https://github.com/datacenter
    nb_args = len(args)
    if nb_args > 1:
        help_string = color_green + "Version of show ip int br, including subnet masks. No arguments required." + color_normal
        m = re.match('__cli_script.*help', args[1])
        if m:
                # user entered "source ?" with no parameters: display script help
                if args[1] == "__cli_script_help":
                    print help_string
                # argument help
                argv = args[2:]
                # dont count last arg if it was partial help (no-space-question-mark)
                if args[1] == "__cli_script_args_help_partial":
                    argv = argv[:-1]
                nb_args = len(argv)
                # only file name provided: use man-page style help
                print "__man_page"
                print help_string

def calcDottedNetmask(mask):
    #Converts a CIDR number into a dotted netmask - i.e. 24 returns
    #CREDIT: http://stackoverflow.com/questions/819355/how-can-i-check-if-an-ip-is-in-a-network-in-python
    bits = 0
    for i in xrange(32-mask,32):
        bits |= (1 << i)
    return "%d.%d.%d.%d" % ((bits & 0xff000000) >> 24, (bits & 0xff0000) >> 16, (bits & 0xff00) >> 8 , (bits & 0xff))


#Return the help if nexus called it (i.e. source ?)

#Grab the interfaces as structured data
interfaces = clid("show ip interface")

#Count the interfaces
intcount = 0
for key in interfaces.keys():
  if 'intf-name' in key:
    intcount += 1

#Define a fixed width table
table = '{:<25}{:<15}{:<5}{:<16}{:<10}{:<10}{:<10}'

#Print table headers
print table.format('Name','IP','CIDR','Mask','Admin','Link','Protocol')

#Loop the interfaces, grab the relevant bits and print each row
for x in range(1,intcount+1):
  name = interfaces['TABLE_intf/intf-name/'+str(x)]
  ip = interfaces['TABLE_intf/prefix/'+str(x)]
  cidr = interfaces['TABLE_intf/masklen/'+str(x)]
  mask = calcDottedNetmask(int(cidr))
  admin = interfaces['TABLE_intf/admin-state/'+str(x)]
  link = interfaces['TABLE_intf/link-state/'+str(x)]
  protocol = interfaces['TABLE_intf/proto-state/'+str(x)]
  print table.format(name,ip,cidr,mask,admin,link,protocol)

We know technology can be a bother, and that’s why we are here to help with all your IT needs, no matter how big or small.

Our goal is to make sure that your business has a reliable infrastructure in place so you can focus on what matters most – running your company! 

So if you need any help at all, book a 15 minute discovery call with one of our experts today. We’ll be happy to lend a hand! 

Select Service

Discovery Call 15 minutes

Select time

Select a service and date to see available times.

Tell us who we are meeting

Can we have a heads up on roughly what you want to talk about please?

Initial consult

Duration: 1 hour
Not sure what you need? Grab 60 minutes with us and we will work with you to understand your goals, and to develop a proposal and price estimate.

Leave a Reply

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

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