This guide provides information needed to use the Python Software Development Kit (SDK) to develop programs for the Cisco Nexus 9000 Series switches operating in Cisco NX-OS Software mode. This guide includes descriptions of the application programming interface (API) classes and methods.

Note: This guide is intended for users who are familiar with the Python programming language and who have experience configuring Cisco Nexus switches. For detailed configuration information, refer to other Cisco documentation, such as Cisco Nexus 9000 Series NX-OS configuration guides and CLI command references.

About the Python Programming Language

The Python interpreter and the extensive standard library are freely available in source or binary form for all major platforms from the Python website at www.python.org. The Python website also distributes and links to many free third-party Python modules, programs and tools, and additional documentation.

The Cisco Nexus 9000 Series switches support all of the features available in Python v2.7.5.

Features of Nexus 9000 Python Scripting

The Python scripting capability on the Cisco Nexus 9000 Series switches allows you to perform the following tasks:

  • Run a script to verify configuration on switch bootup.

  • Back up a configuration.

  • Perform proactive congestion management by monitoring and responding to buffer utilization characteristics.

  • Integrate with the Power-On Auto Provisioning for EEM modules.

  • Perform a job at a specific time interval (such as Port Auto Description).

  • Programmatically access the switch command-line interface (CLI) to perform various tasks.

  • Python can also be accessed from the Bash shell.

Getting Started with the Cisco Nexus 9000 Series Python SDK

Installing Python and the Python API

The Python interpreter and the Cisco Python SDK are available by default in the Cisco NX-OS software. Standard Python packages are included. Unless you require additional Python packages, no further installation is necessary.

Cisco Python Package

The Cisco Python SDK provides a cisco Python package that enables access to many core network device modules, such as interfaces, VLANs, ACLs, and routes.

The methods and functions in the cisco Python package are implemented in Python source files included with the SDK package. Many of these files have documentation embedded within the source code. In the Python source files, documentation is contained in documentation strings, bracketed by three back-ticks, or ```. Some source files and methods are for internal use and do not have embedded documentation.

Using Python

Entering the Python Shell

switch# python

Python 2.7.5 (default, Oct  8 2013, 23:59:43)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> exit()
switch#

To enter the Python shell, enter the python command from the NX-OS command line with no parameters as shown in the example.

Note: While you can run Python directly from the NX-OS command line, we recommend that you run it from the Guest Shell, a container environment, which is described later in this document.

To exit the Python shell, type exit().

Importing the cisco Python Package and Other Modules

>>> import cisco
>>> from cisco.acl import *

Import the cisco Python package as shown in the example. From the cisco package, import individual modules as needed using

from cisco.module_name import *

where module_name is the name of the individual module. In the example, the ACL module is imported.

>>> from cli import *   
>>> import json

Other useful modules include the cli module and the json module.

Accessing Python Help

>>> help()

To display Python help, enter help() at the Python prompt. In Python help mode, enter modules to list the available Python modules.

>>> import json
>>> help(json)

To display help on a specific Python module, enter help (module_name) where module_name is the name of the for which you are requesting help. For example, enter help (json) to display help on the json module.

After you have imported the cisco package, you can display its help by entering help (cisco) at the Python prompt. To display help on a specific module in the Cisco Python package, enter help (cisco.module_name) where module_name is the name of the module. For example, to display help on the Cisco ACL module, enter help (cisco.acl).

>>> help(cisco)
>>> help(cisco.acl)

Running Python Code

>>> cli('configure terminal ; interface loopback 5 ; no shut')
''
>>> intflist=json.loads(clid('show interface brief'))
>>> i=0
>>> while i < len (intflist['TABLE_interface']['ROW_interface']):
...    intf=intflist['TABLE_interface']['ROW_interface'][i]
...    i=i+1
...    if intf['state'] == 'up':
...       print intf['interface']
...
mgmt0
loopback2
loopback5

After starting Python and importing the required packages and modules, you can run Python scripts directly or you can enter blocks of Python code and run the code.

The example shows how to query the interfaces running on the switch.

You can enter lines of Python code to execute a block of code. A colon (":") at the end of a line tells the Python interpreter that the subsequent lines will form a code block. After the colon, you must indent the subsequent lines in the block, following Python indentation rules. When you have typed the block, press return twice to execute the code.

You can run stored scripts in non-interactive mode from the switch CLI, as described in "Executing Scripts".

Display Formats

When you run CLI commands using the Python interpreter, you can use methods within the cli class to format the output displayed on the console. The following examples show several ways to format the command output.

Example 1: Using clip

>>> cli("conf ; interface loopback 1")
''
>>> clip ('where detail')
  mode:
  username:            admin
  vdc:                 TSI-N9508-stand-alone
  routing-context vrf: default

The clip method allows you to display multiple lines of output.

Example 2: Using 'where detail' with the cli Method

>>> cli ("conf ; interface loopback 1")
''
>>> cli('where detail')
'  mode:                \n  username:            admin\n  vdc:                 T                                                                                                             SI-N9508-stand-alone\n  routing-context vrf: default\n'

Example 3: Using 'where detail' with a Variable and the cli Method

>>> cli("conf ; interface loopback 1")
''
>>> r = cli ('where detail') ; print r
  mode:
  username:            admin
  vdc:                 TSI-N9508-stand-alone
  routing-context vrf: default

Example 4: Using JSON to Display Output

You can use JSON to display particularly long output, as shown in the following example:

>>> out=json.loads(clid('show version'))
>>> for k in out.keys():
...    print "%30s = %s" % (k, out[k])
...
                kern_uptm_secs = 1
                kick_file_name = bootflash:///n9000-dk9.7.0.3.I2.0.410.bin
                    rr_service = None
                     module_id = Supervisor Module
                   kick_tmstmp = 06/21/2015 13:03:15
                bios_cmpl_time = 09/10/2014
                bootflash_size = 20971520
             kickstart_ver_str = 7.0(3)I2(1) [build 7.0(3)I2(0.410)]
                kick_cmpl_time = 6/21/2015 5:00:00
                    chassis_id = Nexus9000 C9508 (8 Slot) Chassis
                 proc_board_id = SAL1733BHLY
                        memory = 16401776
                  manufacturer = Cisco Systems, Inc.
                kern_uptm_mins = 45
                  bios_ver_str = 08.06
                      cpu_name = Intel(R) Xeon(R) CPU E5-2403 0 @ 1.80GHz
                 kern_uptm_hrs = 6
                      rr_usecs = 355035
                    rr_sys_ver = 7.0(3)I1(2)
                     rr_reason = Reset Requested by CLI command reload
                      rr_ctime = Wed Jul  8 18:50:02 2015
                    header_str = Cisco Nexus Operating System (NX-OS) Software

TAC support: https://www.cisco.com/tac
Copyright (C) 2002-2015, Cisco and/or its affiliates.
All rights reserved.
The copyrights to certain works contained in this software are
owned by other third parties and used and distributed under their own
licenses, such as open source.  This software is provided "as is," and unless
otherwise stated, there is no warranty, express or implied, including but not
limited to warranties of merchantability and fitness for a particular purpose.
Certain components of this software are licensed under
the GNU General Public License (GPL) version 2.0 or
GNU General Public License (GPL) version 3.0  or the GNU
Lesser General Public License (LGPL) Version 2.1 or
Lesser General Public License (LGPL) Version 2.0.
A copy of each such license is available at
https://www.opensource.org/licenses/gpl-2.0.php and
https://opensource.org/licenses/gpl-3.0.html and
https://www.opensource.org/licenses/lgpl-2.1.php and
https://www.gnu.org/licenses/old-licenses/library.txt.
                     host_name = TSI-N9508-stand-alone
                      mem_type = kB
                kern_uptm_days = 28
>>>

Executing Scripts

switch# python test.py

You can run a Python script in non-interactive mode by providing the Python script name as an argument to the Python CLI command. Python scripts must be placed under the bootflash or volatile scheme.

To execute a Python script, enter the python command followed by the filename of the script followed by any arguments for the script, as shown in this example:

switch# python bootflash:scripts/deltaCounters.py Ethernet1/1 1 5

switch# python bootflash:scripts/deltaCounters.py Ethernet1/1 1 5

A maximum of 32 command line arguments for the Python script are allowed with the python CLI command.

Several example scripts are provided in "Example Scripts".

Using the source Command

The Cisco Nexus 9000 Series device supports the source CLI command for running Python scripts. The bootflash:scripts directory is the default script directory for the source CLI command.

switch# source deltaCounters Ethernet1/1 1 5

Using the source command, the previous example could also be executed as follows:

switch# source deltaCounters Ethernet1/1 1 5

The source command is helpful when executing compound commands from the CLI. The following example shows a source command following a pipe operator ("|"), allowing a Python script to receive input from another CLI command:

switch# show running-config | source sys/cgrep policy-map

switch# show running-config | source sys/cgrep policy-map