Wednesday, November 28, 2012

Cisco Nexus 3K with Python - Part 2

A friend passed along the latest Cisco Nexus 3K API list:
http://www.cisco.com/en/US/docs/switches/datacenter/nexus3000/sw/python/api/503_U41/API_functions.html

Looks pretty good, at least a step in the right direction, IMHO.

I have been playing with Cisco's interpreter a little more to do scheduled jobs using Python's sched module in the standard library. Here is a simple example of how to change the hostname of the router, this can obviously made into a static file that sits in the bootflash and/or include show commands, etc. The 'scheduler.enter()' method takes the first attribute as the delay in seconds, the 'scheduler.enterabs()' method takes the first attribute as Epoch time.

Did I mention the lack of editor directly in the Cisco device drives me nuts?

Here is the example:

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 cisco, sched, time
>>> scheduler = sched.scheduler(time.time, time.sleep)
>>> def change_hostname(name):
...     print "change hostname to switch_new"
...     cisco.cli("config t")
...     cisco.cli("hostname switch_new")
...     cisco.cli("exit")
...
>>> scheduler.enter(30, 1, change_hostname, ('first',))
Event(time=<blah>, priority=1, action=<function change_hostname at <whatever>>, argument=('first',))
>>> scheduler.run() # 30 seconds passed
 change hostname to switch_new
>>>
>>> exit()
switch_new# <<<<< the hostname is changed

In case you are wondering, here is how to find the Epoch time in Python:


>>> import datetime, time
>>> laterDate = datetime.datetime(2012, 12, 15, 13, 00, 00)
>>> time.mktime(laterDate.timetuple())
1355576400.0
>>> 
Here are more information and the tutorials I used:
http://www.doughellmann.com/PyMOTW/sched/index.html#module-sched
http://pleac.sourceforge.net/pleac_python/datesandtimes.html


 Happy scripting! :)



3 comments:

  1. This is a better use of the function, you can pass in the new hostname as a string via name and you function is re-usable, in fact you could (and should) do the same for hostname and have two input variables in your function.

    def change_hostname(name):
    ... print "change hostname to %s" % (name)
    ... cisco.cli("config t")
    ... cmd = "hostname %s" % (name)
    ... cisco.cli(cmd)
    ... cisco.cli("exit")

    ReplyDelete
  2. Thanks Peter, indeed that is a better way, absolutely.

    I don't remember now, but I 'think' that may have been my intention when created the function, else would've just left the parameter blank, like, change_hostname(). I had to sanitize the script quit a bit because I did it in the work lab. But it could also be the Monday morning quarterback in me. :)

    Cheers.

    ReplyDelete