Monday, December 3, 2012

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

In Part 1 and Part 2 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- 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('', '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 Eric
Hello Eric
switch# python Eric John
Hello Eric
Hello John
switch# python Eric John Peter
Hello Eric
Hello John
Hello Peter

Combined with the Cli alias in Cisco NX-OS,, you can create your own command:

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

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!

No comments:

Post a Comment