As we already wrote, the results of a survey conducted by our team show that network scripting and automation still aren’t the number one priority in the world of Network Engineers. It is understandable, after all. Many of us simply do not have the time to venture into new adventures. There is always new documentation to fill, new tasks and projects, learning the new technologies or expanding the knowledge about them. It all takes time.
In my last article, I’ve wrote about ways to automate the provisioning of new Nexus devices. In this one I will talk about the practical ways you can use programming languages such as Python or Bash.
So what do you need to start learning? Well, it’s easy: a bit of good will, time and dedication, as with all the other stuff in life. How badly you need it? That is purely based on your working environment, career goals and ambition. But it can really neat. And I’ll show you some easy examples to fire up your imagination.
How Much Expertise is Really Needed?
I’ll be honest, the answer is completely relative. It’s certain that you need to invest a lot of time to really master a new technique or a technology. So it can probably take a while to really get into Python that much to be able to keep up with serious networking projects. So it’s generally a good idea to seek professional help in those occasions.
But the thing is you don’t have to be a Python Jedi to make your life easier.. By attending some online classes and/or reading a book or two, followed by some labbing, of course, you should be able to quickly grasp some basic concepts and start utilizing them, creating your own little tricks.
For example you can create commands that will do stuff for you. Really cool stuff that can save you from going through heaps of configuration lines looking for an interface where some command is applied on.
Python – Programming Language of Choice
Python has became a programming language of choice for Network Engineers who want to be on top of their game. It is relatively easy to learn, compared to other types of code at least. And you can use it to fully unleash the power of your Nexus switches, automating their deployment and functions across data centers.
One of Python’s main assets is it’s quick and elegant coding and an easy to read format. You can almost read the code like you are reading a text, which makes Python somehow an user friendly programming language. It’s dynamic typing provides great flexibility that you can apply on your Nexus devices.
Parsing Your Show Commands
Filtering data displayed after entering show commands is one of my favorite ways to use Python. It’s not so hard to learn basic syntaxes and Python logic (which tries to be obvious, not obscure) and apply them to your scripts.
Lot of show commands display a tons of data, but you only need a few lines. For example, commonly used command ‘show version’ is usually executed only to find the the model of your Cisco device. But you will get a whole page of unwanted information and then you’ll typically scroll to the top of the page, trying to find what you want.
So, a good example of Python use would be a script that displays only the needed parts of ‘show version’ command or only certain information from the ‘show interface’ like the MTU size or interface state. So let’s look into some examples of what you can do to enhance your Cisco Nexus experience.
Example of Python Script to Quickly Enable and Monitor NX-API Debugs
#!/usr/bin/env python # # Copyright (C) 2013 Cisco Systems Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # This script can be used to quickly and easily enable and monitor nx-api # sessions and debugs on a Nexus 9000 Standalone Switch. If the script # is copied into bootflash:///scripts, it can be run as: # # source enable_and_tail_enhanced_nxapi_debugs # import os import sys import time def touch(path): """ Touch the path, which means create it if it doesn't exist and set the path's utime. """ with open(path, 'a'): os.utime(path, None) def get_root(file): """ Returns the root filesystem designator in a non-platform-specific way """ somepath = os.path.abspath(sys.executable) (drive, path) = os.path.splitdrive(somepath) while 1: (path, directory) = os.path.split(path) if not directory: break return drive + path def print_file_from(filename, pos): """ Determine where to start printing from within a file """ with open(filename, 'rb') as fh: fh.seek(pos) while True: chunk = fh.read(8192) if not chunk: break sys.stdout.write(chunk) def _fstat(filename): """ stat the file """ st_results = os.stat(filename) return (st_results, st_results) def _print_if_needed(filename, last_stats): changed = False #Find the size of the file and move to the end tup = _fstat(filename) if last_stats[filename] != tup: changed = True print_file_from(filename, last_stats[filename]) last_stats[filename] = tup return changed def multi_tail(filenames, stdout=sys.stdout, interval=1, idle=10): S = lambda (st_size, st_mtime): (max(0, st_size - 124), st_mtime) last_stats = dict((fn, S(_fstat(fn))) for fn in filenames) last_print = 0 while 1: changed = False for filename in filenames: if _print_if_needed(filename, last_stats): changed = True if changed: if idle > 0: last_print = time.time() else: if idle > 0 and last_print is not None: if time.time() - last_print >= idle: last_print = None time.sleep(interval) # Build a path to the logflag file in a platform non-specific way nxapi_logs_directory = os.path.join(get_root(sys.executable), 'var', 'nginx', 'logs') nxapi_enable_debug_file = os.path.join(nxapi_logs_directory, "logflag") # Touch that file so enhanced nxapi debugs start to be logged touch(nxapi_enable_debug_file) print "Tailing the access.log, error.log and the nginx.log, use cntl-c (^C)" print "to exit." # Tail the logs logs =  logs.append(os.path.join(nxapi_logs_directory, "access.log")) logs.append(os.path.join(nxapi_logs_directory, "error.log")) logs.append(os.path.join(nxapi_logs_directory, "nginx.log")) try: multi_tail(logs) except KeyboardInterrupt: pass # Clean up try: os.remove(nxapi_enable_debug_file) except: pass
I hope I’ve got you interested enough. If you’re keen on starting your learning adventure, you can try out Kirk Byers ‘Python for Network Engineers’ video course. It’s recommended by many experts.
Also you can always start with the ‘Foundations of Python Network Programming” book by John Goerzen and Brandon Rhodes.
So, what are you waiting for? Let go you imagination and find cool and useful ways to use Python in your Network Engineering tasks.
And don’t forget to share them with us in the comment sections.