Python API. About the Python API. Using Python. Cisco Python Package. About the Python API, page 1 Using Python, page 1



Similar documents
ISE TACACS+ Configuration Guide for Cisco NX-OS Based Network Devices. Secure Access How-to User Series

Configuring SSH and Telnet

Enabling Remote Access to the ACE

Configuring Password Encryption

Configuring Password Encryption

Configuring System Message Logging

Configuring the Firewall Management Interface

Backing Up and Restoring Data

Configuring NetFlow. Information About NetFlow. NetFlow Overview. Send document comments to CHAPTER

Configuring NetFlow. Information About NetFlow. NetFlow Overview. Send document comments to CHAPTER

Configuring the Scheduler

Using LiveAction with Cisco Secure ACS (TACACS+ Server)

Command Line Interface User Guide for Intel Server Management Software

Configuring ECMP for Host Routes

Configuring NTP. Information About NTP. NTP Overview. Send document comments to CHAPTER

Network Programmability and Automation with Cisco Nexus 9000 Series Switches

Managing Storage Services Modules

Licensing Cisco NX-OS Software Features

Configuring Network QoS

Cisco ISE Command-Line Interface

Configuring Auto Policy-Based Routing

Telnet, Console and AUX Port Passwords on Cisco Routers Configuration Example

Cisco Nexus 5548UP. Switch Configuration Guide for Dell PS Series SANs. A Dell Deployment and Configuration Guide

Configuring CSS Remote Access Methods

Router Lab Reference Guide

Connecting to the Firewall Services Module and Managing the Configuration

- The PIX OS Command-Line Interface -

Table of Contents. Cisco Using the Cisco IOS Firewall to Allow Java Applets From Known Sites while Denying Others

Configuring NetFlow. Information About NetFlow. Send document comments to CHAPTER

Configuring NetFlow-lite

Configuring Static and Dynamic NAT Translation

Configuring Role-Based Access Control

Configuring Class Maps and Policy Maps

Send document comments to

Lab: Basic Router Configuration

HTTP 1.1 Web Server and Client

Configuring DHCP Snooping and IP Source Guard

ICND IOS CLI Study Guide (CCENT)

Troubleshooting the Firewall Services Module

Chapter 7 Configuring Trunk Groups and Dynamic Link Aggregation

Configuring System Message Logging

How To Configure Rmon On Cisco Me 2600X On Ios 2.5A (Cisco) With A Network Monitor On A Network Device (Network) On A Pnet (Network Monitor) On An Ip

Embedded Event Manager Commands

Lab Configure Local AAA on Cisco Router

Administering the Network Analysis Module. Cisco IOS Software. Logging In to the NAM with Cisco IOS Software CHAPTER

JUNOS Command Line Interface. Copyright 2003 Juniper Networks, Inc. 1

Configuring PROFINET

Traffic Mirroring Commands on the Cisco IOS XR Software

Configuring MPLS Hub-and-Spoke Layer 3 VPNs

Application Centric Infrastructure Object-Oriented Data Model: Gain Advanced Network Control and Programmability

Chapter 2 Quality of Service (QoS)

Brocade to Cisco Comparisons

Configuring the Cisco IOS In-Service Software Upgrade Process

Chapter 7 Lab 7-1, Configuring Switches for IP Telephony Support

Monitoring GSS Operation

Traffic Mirroring Commands on the Cisco ASR 9000 Series Router

Configuring Cisco Nexus 5000 Switches Course DCNX5K v2.1; 5 Days, Instructor-led

Cisco Nexus 7000 Series NX-OS CLI Management Best Practices Guide

Lab Configuring Syslog and NTP (Instructor Version)

Using the Advanced GUI

Using Cisco IOS Software

Skills Assessment Student Training Exam

Troubleshooting the Firewall Services Module

Basic Configuration of the Cisco Series Internet Router

Common Services Platform Collector 2.5 Quick Start Guide

Installing the Cisco Nexus 1000V for Microsoft Hyper-V

Lab Advanced Telnet Operations

Configuring System Message Logging

Securing Networks with PIX and ASA

Basic System. Vyatta System. REFERENCE GUIDE Using the CLI Working with Configuration System Management User Management Logging VYATTA, INC.

Migrate from Cisco Catalyst 6500 Series Switches to Cisco Nexus 9000 Series Switches

Note: This case study utilizes Packet Tracer. Please see the Chapter 5 Packet Tracer file located in Supplemental Materials.

An Introduction to Service Containers

Implementing Secure Shell

Using the Command-Line Interface

ROLE-BASED COMMAND-LINE INTERFACE ACCESS

TIBCO Spotfire Server Migration. Migration Manual

Installation Guide for Basler pylon 2.3.x for Linux

Transferring Files Using HTTP or HTTPS

AutoQoS. Prerequisites for AutoQoS CHAPTER

SNMP, RMON, and Alarm Configuration

Lab Review of Basic Router Configuration with RIP. Objective. Background / Preparation. General Configuration Tips

Configuring EtherChannels

File Transfers. Contents

WildFire Cloud File Analysis

Chapter 3 Using Access Control Lists (ACLs)

Configuring DHCP Snooping

Computer Networks Administration Help Manual Sana Saadaoui Jemai Oliver Wellnitz

Configuring System Message Logging

ICND1 Lab Guide Interconnecting Cisco Networking Devices Part 1 Version 2.0. Labs powered by

Configuring iscsi Multipath

Lab Configure Basic AP Security through IOS CLI

Configuring Basic Settings

Enabling NetFlow and NetFlow Data Export (NDE) on Cisco Catalyst Switches

Volume SYSLOG JUNCTION. User s Guide. User s Guide

Backup and Recovery Procedures

Running and Scheduling QGIS Processing Jobs

Using the Cisco IOS Command Line Interface

7750 SR OS System Management Guide

Connect the Host to attach to Fast Ethernet switch port Fa0/2. Configure the host as shown in the topology diagram above.

Transcription:

About the, page 1 Using Python, page 1 About the Python is an easy to learn, powerful programming language. It has efficient high-level data structures and a simple but effective approach to object-oriented programming. Python's elegant syntax and dynamic typing, together with its interpreted nature, make it an ideal language for scripting and rapid application development in many areas on most platforms. The Python interpreter and the extensive standard library are freely available in source or binary form for all major platforms from the Python website: http://www.python.org/ The same site also contains distributions of and pointers to many free third-party Python modules, programs and tools, and additional documentation. The Cisco Nexus 9000 Series devices support Python v2.7.5 in both interactive and non-interactive (script) modes. The Python scripting capability on the Cisco Nexus 9000 Series devices gives programmatic access to the device's command-line interface (CLI) to perform various tasks and PowerOn Auto Provisioning (POAP) or Embedded Event Manager (EEM) actions. Python can also be accessed from the Bash shell. The Python interpreter is available in the Cisco NX-OS software. Using Python This section describes how to write and execute Python scripts. Cisco Python Package Cisco NX-OS provides a Cisco Python package that enables access to many core network device modules, such as interfaces, VLANs, VRFs, ACLs and routes. You can display the details of the Cisco Python package 1

Using the CLI Command APIs by entering the help() command. To obtain additional information about the classes and methods in a module, you can run the help command for a specific module. For example, help(cisco.interface) displays the properties of the cisco.interface module. The following is an example of how to display information about the Cisco python package: import cisco help(cisco) Help on package cisco: NAME cisco FILE /isan/python/scripts/cisco/ init.py PACKAGE CONTENTS acl bgp cisco_secret cisco_socket feature interface key line_parser md5sum nxcli ospf routemap routes section_parser ssh system tacacs vrf CLASSES builtin.object cisco.cisco_secret.ciscosecret cisco.interface.interface cisco.key.key Using the CLI Command APIs The Python programming language uses three APIs that can execute CLI commands. The APIs are available from the Python CLI module. These APIs are listed in the following table. You need to enable the APIs with the from cli import * command. The arguments for these APIs are strings of CLI commands. To execute a CLI command through the Python interpreter, you enter the CLI command as an argument string of one of the following APIs: 2

Invoking the Python Interpreter from the CLI Table 1: CLI Command APIs API cli() Example: string = cli ( cli-command ) clid() Example: json_string = clid ( cli-command ) clip() Example: clip ( cli-command ) Description Returns the raw output of CLI commands, including control/special characters. Note The interactive Python interpreter prints control/special characters 'escaped'. A carriage return is printed as '\n' and gives results that might be difficult to read. The clip() API gives results that are more readable. For CLI commands that support XML, this API returns JSON output. Note An exception is thrown when XML is not used. This API can be useful when searching the output of show commands. Prints the output of the CLI command directly to stdout and returns nothing to Python. Note clip ( cli-command ) is equivalent to r=cli( cli-command ) print r When two or more commands are run individually, the state is not persistent from one command to subsequent commands. In the following example, the second command fails because the state from the first command does not persist for the second command: cli("conf t") cli("interface eth4/1") When two or more commands are run together, the state is persistent from one command to subsequent commands. In the following example, the second command is successful because the state persists for the second and third commands: cli("conf t ; interface eth4/1 ; shut") Note Commands are separated with " ; " as shown in the example. (The ; must be surrounded with single blank characters.) Invoking the Python Interpreter from the CLI The following example shows how to invoke Python from the CLI: 3

Display Formats Note The Python interpreter is designated with the "" or " " prompt. 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. import json 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 Ethernet2/7 Ethernet4/7 loopback0 loopback5 Display Formats The following examples show various display formats using the s: Example 1: cli("conf ; interface loopback 1") '' clip('where detail') mode: username: admin vdc: switch routing-context vrf: default Example 2: cli("conf ; interface loopback 1") '' cli('where detail') ' mode: \n username: admin\n vdc: switch\n routing-context vrf: default\n' Example 3: cli("conf ; interface loopback 1") '' r = cli('where detail') ; print r mode: username: admin vdc: EOR-1 routing-context vrf: default Example 4: import json 4

Non-interactive Python out=json.loads(clid('show version')) for k in out.keys():... print "%30s = %s" % (k, out[k])... kern_uptm_secs = 6 kick_file_name = bootflash:///n9000-dk9.6.1.2.i1.1.bin rr_service = None module_id = Supervisor Module kick_tmstmp = 10/21/2013 00:06:10 bios_cmpl_time = 08/17/2013 bootflash_size = 20971520 kickstart_ver_str = 6.1(2)I1(2) [build 6.1(2)I1(2)] [gdb] kick_cmpl_time = 10/20/2013 4:00:00 chassis_id = Nexus9000 C9508 (8 Slot) Chassis proc_board_id = SAL171211LX memory = 16077872 manufacturer = Cisco Systems, Inc. kern_uptm_mins = 26 bios_ver_str = 06.14 cpu_name = Intel(R) Xeon(R) CPU E5-2403 kern_uptm_hrs = 2 rr_usecs = 816550 rr_sys_ver = None rr_reason = Reset Requested by CLI command reload rr_ctime = Mon Oct 21 00:10:24 2013 header_str = Cisco Nexus Operating System (NX-OS) Software TAC support: http://www.cisco.com/tac Documents: http://www.cisco.com/en/us/products/ps9372/tsd_products_support_series_home.html Copyright (c) 2002-2013, Cisco Systems, Inc. All rights reserved. The copyrights to certain works contained herein are owned by other third parties and are used and distributed under license. Some parts of this software are covered under the GNU Public License. A copy of the license is available at http://www.gnu.org/licenses/gpl.html. host_name = switch mem_type = kb kern_uptm_days = 0 Non-interactive Python A Python script can run 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. A maximum of 32 command line arguments for the Python script are allowed with the Python CLI command. The Cisco Nexus 9000 Series device also supports the source CLI command for running Python scripts. The bootflash:scripts directory is the default script directory for the source CLI command. The following example shows a script and how to run it: switch# show file bootflash:deltacounters.py #!/isan/bin/python from cli import * import sys, time ifname = sys.argv[1] delay = float(sys.argv[2]) count = int(sys.argv[3]) cmd = 'show interface ' + ifname + ' counters' out = json.loads(clid(cmd)) rxuc = int(out['table_rx_counters']['row_rx_counters'][0]['eth_inucast']) rxmc = int(out['table_rx_counters']['row_rx_counters'][1]['eth_inmcast']) rxbc = int(out['table_rx_counters']['row_rx_counters'][1]['eth_inbcast']) txuc = int(out['table_tx_counters']['row_tx_counters'][0]['eth_outucast']) txmc = int(out['table_tx_counters']['row_tx_counters'][1]['eth_outmcast']) txbc = int(out['table_tx_counters']['row_tx_counters'][1]['eth_outbcast']) 5

Running Scripts with Embedded Event Manager print 'row rx_ucast rx_mcast rx_bcast tx_ucast tx_mcast tx_bcast' print '=========================================================' print ' %8d %8d %8d %8d %8d %8d' % (rxuc, rxmc, rxbc, txuc, txmc, txbc) print '=========================================================' i = 0 while (i < count): time.sleep(delay) out = json.loads(clid(cmd)) rxucnew = int(out['table_rx_counters']['row_rx_counters'][0]['eth_inucast']) rxmcnew = int(out['table_rx_counters']['row_rx_counters'][1]['eth_inmcast']) rxbcnew = int(out['table_rx_counters']['row_rx_counters'][1]['eth_inbcast']) txucnew = int(out['table_tx_counters']['row_tx_counters'][0]['eth_outucast']) txmcnew = int(out['table_tx_counters']['row_tx_counters'][1]['eth_outmcast']) txbcnew = int(out['table_tx_counters']['row_tx_counters'][1]['eth_outbcast']) i += 1 print '%-3d %8d %8d %8d %8d %8d %8d' % \ (i, rxucnew - rxuc, rxmcnew - rxmc, rxbcnew - rxbc, txucnew - txuc, txmcnew - txmc, txbcnew - txbc) switch# python bootflash:deltacounters.py Ethernet1/1 1 5 row rx_ucast rx_mcast rx_bcast tx_ucast tx_mcast tx_bcast ========================================================= 0 791 1 0 212739 0 ========================================================= 1 0 0 0 0 26 0 2 0 0 0 0 27 0 3 0 1 0 0 54 0 4 0 1 0 0 55 0 5 0 1 0 0 81 0 switch# The following example shows how a source command specifies command-line arguments. In the example, policy-map is an argument to the cgrep python script. The example also shows that a source command can follow after the pipe operator (" "). switch# show running-config source sys/cgrep policy-map policy-map type network-qos nw-pfc policy-map type network-qos no-drop-2 policy-map type network-qos wred-policy policy-map type network-qos pause-policy policy-map type qos foo policy-map type qos classify policy-map type qos cos-based policy-map type qos no-drop-2 policy-map type qos pfc-tor-port Running Scripts with Embedded Event Manager On Cisco Nexus 9000 Series devices, embedded event manager (EEM) policies support Python scripts. The following example shows how to run a Python script as an EEM action: An EEM applet can include a Python script with an action command. switch# show running-config eem!command: show running-config eem!time: Sun May 1 14:40:07 2011 version 6.1(2)I2(1) event manager applet a1 event cli match "show clock" action 1 cli python bootflash:pydate.py action 2 event-default 6

Python Integration with Cisco NX-OS Network Interfaces You can search for the action triggered by the event in the log file by running the show file logflash:event_archive_1 command. switch# show file logflash:event_archive_1 last 33 eem_event_time:05/01/2011,19:40:28 event_type:cli event_id:8 slot:active(1) vdc:1 severity:minor applets:a1 eem_param_info:command = "exshow clock" Starting with policy a1 Python 2011-05-01 19:40:28.644891 Executing the following commands succeeded: python bootflash:pydate.py PC_VSH_CMD_TLV(7679) with q Python Integration with Cisco NX-OS Network Interfaces On Cisco Nexus 9000 Series devices, Python is integrated with the underlying Cisco NX-OS network interfaces. You can switch from one virtual routing context to another by setting up a context through the cisco.vrf.set_global_vrf() API. The following example shows how to retrieve an HTML document over the management interface of a Cisco Nexus 9000 Series device. You can also establish a connection to an external entity over the inband interface by switching to a desired virtual routing context. 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. import urllib2 from cisco.vrf import * set_global_vrf('management') page=urllib2.urlopen('http://172.23.40.211:8000/welcome.html') print page.read() Hello Cisco Nexus 9000 import cisco help(cisco.vrf.set_global_vrf) Help on function set global vrf in module cisco.vrf: set global vrf(vrf) Sets the global vrf. Any new sockets that are created (using socket.socket) will automatically get set to this vrf (including sockets used by other python libraries). Arguments: vrf: VRF name (string) or the VRF ID (int). Returns: Nothing Cisco NX-OS Security with Python Cisco NX-OS resources are protected by the Cisco NX-OS Sandbox layer of software and by the CLI role-based access control (RBAC). All users associated with a Cisco NX-OS network-admin or dev-ops role are privileged users. Users who are granted access to Python with a custom role are regarded as non-privileged users. Non-privileged users have 7

Cisco NX-OS Security with Python a limited access to Cisco NX-OS resources, such as file system and Bash commands. Privileged users have greater access to all the resources of Cisco NX-OS. Examples of Security and User Authority The following example shows how a privileged user runs commands: 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. import os os.system('whoami') admin 0 f=open('/tmp/test','w') f.write('hello from python') f.close() r=open('/tmp/test','r') print r.read() hello from python r.close() The following example shows a non-privileged user being denied access: 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. import os os.system('whoami') system(whoami): rejected! -1 f=open('/tmp/test','r') Permission denied. Traceback (most recent call last): File "<stdin>", line 1, in <module> IOError: [Errno 13] Permission denied: '/tmp/test' RBAC controls CLI access based on the login user privileges. A login user's identity is given to Python that is invoked from the CLI shell or from Bash. Python passes the login user's identity to any subprocess that is invoked from Python. The following is an example for a privileged user: cli('show clock') '11:28:53.845 AM UTC Sun May 08 2011\n' cli('configure terminal ; vrf context myvrf') '' clip('show running-config l3vm')!command: show running-config l3vm!time: Sun May 8 11:29:40 2011 version 6.1(2)I2(1) interface Ethernet1/48 vrf member blue interface mgmt0 vrf member management vrf context blue vrf context management vrf context myvrf 8

Cisco NX-OS Security with Python The following is an example for a non-privileged user: cli('show clock') '11:18:47.482 AM UTC Sun May 08 2011\n' cli('configure terminal ; vrf context myvrf2') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/isan/python/scripts/cli.py", line 20, in cli raise cmd_exec_error(msg) errors.cmd_exec_error: '% Permission denied for the role\n\ncmd exec error.\n' The following example shows an RBAC configuration: switch# show user-account user:admin this user account has no expiry date roles:network-admin user:pyuser this user account has no expiry date roles:network-operator python-role switch# show role name python-role Example of Running Script with Scheduler The following example shows a Python script that is running the script with the scheduler feature: #!/bin/env python from cli import * from nxos import * import os switchname = cli("show switchname") try: user = os.environ['user'] except: user = "No user" pass msg = user + " ran " + file + " on : " + switchname print msg py_syslog(1, msg) # Save this script in bootflash:///scripts switch# conf t Enter configuration commands, one per line. End with CNTL/Z. switch(config)# feature scheduler switch(config)# scheduler job name testplan switch(config-job)# python bootflash:///scripts/testplan.py switch(config-job)# exit switch(config)# scheduler schedule name testplan switch(config-schedule)# job name testplan switch(config-schedule)# time start now repeat 0:0:4 Schedule starts from Mon Mar 14 16:40:03 2011 switch(config-schedule)# end switch# term mon 2011 Mar 14 16:38:03 switch %VSHD-5-VSHD_SYSLOG_CONFIG_I: Configured from vty by admin on 10.19.68.246@pts/2 switch# show scheduler schedule Schedule Name : testplan ------------------------------ User Name : admin Schedule Type : Run every 0 Days 0 Hrs 4 Mins Start Time : Mon Mar 14 16:40:03 2011 Last Execution Time : Yet to be executed ----------------------------------------------- Job Name Last Execution Status ----------------------------------------------- testplan -NA- ============================================================================== 9

Cisco NX-OS Security with Python switch# switch# 2011 Mar 14 16:40:04 switch %USER-1-SYSTEM_MSG: No user ran /bootflash/scripts/testplan.py on : switch - nxpython 2011 Mar 14 16:44:04 switch last message repeated 1 time switch# 10