Monday, December 3, 2012

Cisco Nexus 3K with Python - Part 3. Extending NX-OS commands

In Part 1 http://blog.pythonicneteng.com/2012/08/cisco-nexus-3k-with-python-part-1.html and Part 2 http://blog.pythonicneteng.com/2012/11/cisco-nexus-3k-with-python-part-2.html of the "Cisco Nexus 3K with Python" gave some taste of running Python scripts within the Cisco Nexus 3000 switch. You might be wondering, what are some of the practical use of them? Lots, I would say.

Here is one way that you can use the Python scripts to extend the current set of commands.

For example, say you want to have a command 'hello' inside of NX-OS, takes the argument and say hello back. Here is a simple way to do that, becuase Cisco doesnt have a native text editor, so I just choose to open a file and write to it:
switch# python
Python 2.7.2 (default, Mar 6 2012, 15:51:12)
[GCC 3.4.3 (MontaVista 3.4.3-25.0.143.0800417 2008-02-22)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
Loaded cisco NxOS lib!
>>> import os
>>> os.chdir("/bootflash")
>>> f = open('helloWorld.py', 'w')
>>> f.write("#!/usr/bin/env python\n")
>>> f.write("import sys\n")
>>> f.write("argvList = sys.argv[1:]\n")
>>> f.write("for argv in argvList:\n")
>>> f.write(" print 'Hello ' + argv\n")
>>> f.close()
>>>
>>> exit()
 Here is what the final script look like, you can choose to write it somewhere else and FTP it to the device:
#!/usr/bin/env python
import sys
argvList = sys.argv[1:]
for argv in argvList:
    print 'Hello ' + argv
You can run it with the normal Python CLI:


switch# python helloWorld.py Eric
Hello Eric
switch# python helloWorld.py Eric John
Hello Eric
Hello John
switch# python helloWorld.py Eric John Peter
Hello Eric
Hello John
Hello Peter
switch#

Combined with the Cli alias in Cisco NX-OS, http://www.cisco.com/en/US/docs/switches/datacenter/sw/4_2/nx-os/fundamentals/command/reference/fnd_commands.html#wp1142080, you can create your own command:


switch(config)# cli alias name hello python helloWorld.py
switch(config)# end
switch# hello Eric John Peter
Hello Eric
Hello John
Hello Peter
switch#



You can essentially write your own NX-OS command set if you wanted to. Lots of possibilities. And by calling the cisco.cli() method in part 2 blog, you can do multiple changes with one script.

Happy scripting!





2 comments: