Python Programming for Cisco Nexus (NX-OS) Series

Before I get into the Python for NX-OS, let me explain a few concepts that I've seen Network Engineers have been struggling with.

DevOps

DevOps is a software development method that combines the Software Development (Apps) and the IT Operations (Systems and Network).

GitHub

GitHub is the largest open source repository in the world. The typical operations that can be done from the Command line in Mac OS are shown below:

mjovanovic$ git

The most commonly used git commands are:
   add        Add file contents to the index
   bisect     Find by binary search the change that introduced a bug
   branch     List, create, or delete branches
   checkout   Checkout a branch or paths to the working tree
   clone      Clone a repository into a new directory
   commit     Record changes to the repository
   diff       Show changes between commits, commit and working tree, etc
   fetch      Download objects and refs from another repository
   grep       Print lines matching a pattern
   init       Create an empty Git repository or reinitialize an existing one
   log        Show commit logs
   merge      Join two or more development histories together
   mv         Move or rename a file, a directory, or a symlink
   pull       Fetch from and integrate with another repository or a local branch
   push       Update remote refs along with associated objects
   rebase     Forward-port local commits to the updated upstream head
   reset      Reset current HEAD to the specified state
   rm         Remove files from the working tree and from the index
   show       Show various types of objects
   status     Show the working tree status
   tag        Create, list, delete or verify a tag object signed with GPG



IDE (Integrated Development Environment)


IDE is like an advanced Text Editor. You may use Notepad++, but when you get deeper into Python – its highly recommended you switch to IDE. There are many, many versions out there, and the one I'm using and I recommend if you're-using Python is PyCharm (There is a community edition, which is free).

API (Application Programming Interface)


API is a set of requirements for the application interaction (how one application should use/interact with another app). The final aim here is to be able to do the Automation.






Again, what is an API? API, or an Application Programming Interface, is just a small webserver answering to xml/json requests. For programming the API interfaces you can use any language you want, and you will need to program/script because both leading SDN solutions on the market (Cisco ACI and VMware NSX) provide the programmability using the API interfaces.

Python can easily be used as a Scripting Language, which is why us, as Network Engineers, would choose it over other Languages. It´s an object oriented language like Java, and it relies heavily on the Exceptions.

So again, a million dollar question is - Why Python?
  • Because it´s Readable (I don’t even want to remember all the code I wrote in PEARL while working for IBM)
  • It´s easy to debug, cause every error has an Exception.
  • It´s suitable for Scripting, which is what we need to automate some of our Networking procedurers, which are by nature repetitive.
  • Procedural Programming is important to understand in order to get what Python is about. It is a set of steps (sub-routines) that are carried out in order to get a certain procedure done.
  • Object Oriented Programming is even more important, because that’s what kind of language Python is. The building blocks are:
    • Methods represent what the Object does.
    • Functions
    • Classes are like Blueprints. They only declare the attributes.
    • Objects (an instance of a class).

There is also a Functional Programming, which is basically stateless; each Function operates independently from one ahother. Luckily, there wont be much about Functional programming here.
Software Development Lifecycle includes an entire methodology, but as Network Engineers, we need just a few core steps:
  • Gather the Requirements, which is probably the most important part. This includes defining the Scope and you should be sticking exactly to the documentation created in this phase.
  • Application Design, which later guides you how to write a code. It helps you break down the code. It´s very usefull to use the already created templates from your previous projects, or from the other designers.
  • Implementation, which means - actually writing the code. Be sure to stick to requirements, and be sure to write the simple patterned code and comment/document your code. Make a personal database of the procedures you frequently use.
  • Testing, and validating your specific parts of the code, and the entire code. When you write an API, which is what us, Network Engineers, will be doing most of the time when we're forced to program, the tests are mandatory.
  • Version Control, if you accidentally delete a part of the code you allways need to have a backup.


REST API Model

REST is is an architecture style for designing networked applications. HTTP/S is used to make the CALLs, and the response will be the simple XML/JSON (popular data formats that are easy to read and parse) formatted information that we will later process.


Bash

TIP: On the VI editor, use “i” to get into Insert mode, and “Esc” to get back to the command mode. Use “/string” to search.
Bash stands for “Bourne-Again SHell”, and it’s the set of Linux commands on the Nexus Switch (End of 2015 – only supported on N9k). Bach enables access to the underlying Linux system on the device and to manage the system:

Nexus9k(config)# feature bash-shell
Nexus9k # run bash

bash-4.2$ whoami
admin
bash-4.2$ pwd
/bootflash/home/admin


TIP: You can use BASH to compile your Python Script, and protect your intellectual property, and prevent it from being modified, using the command “python –m compile FILE.py”. Don’t forget to remove the original (.py) file once you’ve created the compiled one (.pyc).
Bash Scripting can get more advanced too, so if you need to, for example, capture the receive counters of the interfaces:

for I in {1..5}
       do
               echo “RX Counters”
               date
       ifconfig eth1 | grep “RX packets” | cut –d ‘:’ –f2 | cut –d ‘ ‘ –f1 sleep 1
done


The biggest advantage when you compare Scripting with Python and the typical Switch CLI commands copy-paste that we all do is that when Python command fails, it stops and does a clean up.
When you start, you need to import the Cisco Module (library) to Python first:

>> import cli
or
>> from cli import *

*Cisco Module is available ONLY on the Nexus Switches, baked in. You cannot download it from the GitHub.
A procedure would go like this:
-        Write a Python script and copy it to a Bootflash

-        Option 1: Write a EEM, where the ACTION is the execution of the script you wrote
-                           action 1 cli python bootflash:/script.py
-        Option 2: Create a Scheduler, and execute the Python script in the desired moment (“feature scheduler” on the NX-OS).- You need to define a TASK and relate it to a Python script, and define the execution time:

(config)# scheduler job name TASK
(config-job)# python bootflash:/scripts/My_Script.py
(config)# exit

(config)# scheduler schedule name TASK

(config-schedule)# job name TASK
(config-schedule)# time start now repeat 0:0:1


The CLI Command on a Python API has many built-in scripts:
-        cli.cli: Passes CLI configurations, with a “;” as the delimiter between the different lines in the command script
-        cli.clid: returns JSON of the command output, which is more understandable by the Web Developers
-        cli.clip: Prints the command output to the Standard Output

17 comments:

  1. Thanks for sharing this valuable information to our vision. You have posted a trust worthy blog keep sharing.
    Regards,
    Python Training in Chennai|Python Training|Python Training in Chennai

    ReplyDelete
  2. Marvelous blog with tons of valuable information. I gathered some useful information through your blog. Python Training | Data Science with Python Training

    ReplyDelete
  3. Really an amazing post..! By reading your blog post i gained more information.
    Bulk SMS Chennai
    Internet Marketing Company Chennai

    ReplyDelete
  4. Great information shared in this blog. Helps in gaining concepts about new information and concepts. Awesome information provided. Very useful for the beginners.
    CCNA jobs in Hyderabad | CCNA Openings in Hyderabad .

    ReplyDelete
  5. Pretty article! I found some useful information in your blog, it was awesome to read, thanks for sharing this great content to my vision, keep sharing.RPA Training Institute in Chennai | UI Path Training Institute in Chennai | Blue Prism Training Institute in Chennai

    ReplyDelete
  6. Thanks for sharing this informative content on python programming. Very helpful for python developers. Thanks for sharing and keep updating.
    BE/B.Tech Project Center in Chennai | ME/M.Tech Project Center in Chennai | Final Year Project Center in Chennai

    ReplyDelete
  7. Ciitnoida provides Core and java training institute in noida. We have a team of experienced Java professionals who help our students learn Java with the help of Live Base Projects. The object-oriented, java training in noida , class-based build of Java has made it one of most popular programming languages and the demand of professionals with certification in Advance Java training is at an all-time high not just in India but foreign countries too.

    By helping our students understand the fundamentals and Advance concepts of Java, we prepare them for a successful programming career. With over 13 years of sound experience, we have successfully trained hundreds of students in Noida and have been able to turn ourselves into an institute for best Java training in Noida.

    java training institute in noida
    java training in noida
    best java training institute in noida
    java coaching in noida
    java institute in noida

    ReplyDelete
  8. BCA Colleges in Noida

    CIIT Noida provides Sofracle Specialized B Tech colleges in Noida based on current industry standards that helps students to secure placements in their dream jobs at MNCs. CIIT provides Best B.Tech Training in Noida. It is one of the most trusted B.Tech course training institutes in Noida offering hands on practical knowledge and complete job assistance with basic as well as advanced B.Tech classes. CIITN is the best B.Tech college in Noida, greater noida, ghaziabad, delhi, gurgaon regoin .

    At CIIT’s well-equipped Sofracle Specialized M Tech colleges in Noida aspirants learn the skills for designing, analysis, manufacturing, research, sales, management, consulting and many more. At CIIT B.Tech student will do practical on real time projects along with the job placement and training. CIIT Sofracle Specialized M.Tech Classes in Noida has been designed as per latest IT industry trends and keeping in mind the advanced B.Tech course content and syllabus based on the professional requirement of the student; helping them to get placement in Multinational companies (MNCs) and achieve their career goals.

    MCA colleges in Noida we have high tech infrastructure and lab facilities and the options of choosing multiple job oriented courses after 12th at Noida Location. CIIT in Noida prepares thousands of engineers at reasonable B.Tech course fees keeping in mind training and B.Tech course duration and subjects requirement of each attendee.

    Engineering College in Noida"

    ReplyDelete
  9. Thank you for sharing such great information very useful to us.
    Python Training in Gurgaon

    ReplyDelete
  10. This comment has been removed by the author.

    ReplyDelete
  11. Thank you for posting wonderful information which is helpful for who wants this type information
    python training in Hyderabad the best career

    ReplyDelete
  12. Thanks for sharing this valuable information and we collected some information from this blog.
    Python Training in Gurgaon

    ReplyDelete

Most Popular Posts