Chapter 15. Automation and Scripting Tools

Network automation can make your life easier. There are many reasons why IT organizations of all shapes and sizes are adopting network automation. Following are some of them:

Reduced operational costs: Automation can give return on investment for every dollar spent. Automation has the potential to reduce IT department staffing costs while potentially redirecting IT staff efforts to more proactive, business value–generating projects.

Deterministic outcomes: Automation of the network decreases manual, error-prone processes on network configuration and deployment.

Resilient networks: Automation can detect and fix network errors on the fly without manual intervention. This results in more resilient networks.

Faster deployment: Network automation can deploy and upgrade network devices in the network faster without requiring any manual intervention or configuration.

This chapter discusses the following key topics:

EEM Overview: This section discusses EEM policies, event statements, and action statements, along with EEM configuration and verification.

Scheduler: This section discusses the Scheduler concepts, along with Scheduler configuration and verification.

Bash Shell for Cisco NX-OS: This section discusses Bourne Again SHell (Bash) for Cisco NX-OS along with managing feature and patch RPMs.

Guest Shell for Cisco NX-OS: This section discusses how to access the Guest Shell for Cisco NX-OS, the resources used, and the capabilities of the Guest Shell. Later in this section, we discuss how to manage the Guest Shell.

XML: This section discusses XML syntax in detail and includes an example.

JSON: This section briefly discusses JSON syntax and includes an example.

Rest API: This section discusses the concepts of Rest API, including Rest API authentication and Rest API response data. Later in this section, we discuss NX-API in detail, including request and response elements for NX-API. At the end of this section, we describe the NX-API Developer Sandbox.

“Do I Know This Already?” Quiz

The “Do I Know This Already?” quiz enables you to assess whether you should read this entire chapter thoroughly or jump to the “Exam Preparation Tasks” section. If you are in doubt about your answers to these questions or your own assessment of your knowledge of the topics, read the entire chapter. Table 15-1 lists the major headings in this chapter and their corresponding “Do I Know This Already?” quiz questions. You can find the answers in Appendix A, “Answers to the ‘Do I Know This Already?’ Quizzes.”

Table 15-1 “Do I Know This Already?” Section-to-Question Mapping”

Images

Caution

The goal of self-assessment is to gauge your mastery of the topics in this chapter. If you do not know the answer to a question or are only partially sure of the answer, you should mark that question as wrong for purposes of the self-assessment. Giving yourself credit for an answer you correctly guess skews your self-assessment results and might provide you with a false sense of security.


1. What are the major components of the Embedded Event Manager (EEM)? (Choose two answers.)

a. Event statements

b. Job statements

c. Action statements

d. Schedule statements

2. Which of the following actions are NOT supported on EEM configuration? (Choose three answers.)

a. Generate a syslog message.

b. Reload the device.

c. Generate a Python script.

d. Update a counter.

3. Which of the following statements are NOT correct for the Scheduler? (Choose two answers.)

a. You must have network-admin user privileges to configure a scheduled job.

b. You must enable any conditional features before you can configure those features in a job.

c. If you create a schedule and assign jobs and do not configure the time, the job still starts as the Scheduler applies a default timetable.

d. Scheduler features are enabled by default.

4. Which types of timetables for job scheduling are possible in the Scheduler? (Choose three answers.)

a. Monthly

b. Yearly

c. Delta

d. One-time mode

5. Which command enables the Bash shell on Nexus 9000 Series switches?

a. run bash

b. feature bash-shell

c. run bash sudo su

d. username foo shelltype bash

6. Which of the following capabilities is NOT provided to network-admin from within the Guest Shell?

a. Access to Nexus switch bootflash

b. Access to Cisco Nexus switch CLI

c. The ability to install and run 32-bit and 64-bit Windows applications

d. The ability to install and run 32-bit and 64-bit Linux applications

7. Which of the following statements are CORRECT regarding XML? (Choose two answers.)

a. Each XML element must have a start-tag and end-tag.

b. Each XML document can have multiple root elements.

c. XML is not case sensitive.

d. An empty-element tag (or standalone tag) must be properly closed.

8. Which of the following statements is correct with respect to JavaScript Object Notation (JSON)?

a. JSON is more verbose than XML.

b. JSON is used to describe structured data, which doesn’t include arrays, whereas XML includes arrays.

c. JSON is an unordered set of name/value pairs, so it tends to be self-explanatory.

d. A proper JSON object begins with a left bracket [ and ends with a right bracket ].

9. Which of the following are allowed HTTP methods for RESTful API requests? (Choose three answers.)

a. GET

b. POST

c. DOWN

d. PUT

10. Which of the following elements does NOT belong to NX-API Response?

a. chunk

b. output

c. outputs

d. msg

Foundation Topics

EEM Overview

This section describes how to configure the Embedded Event Manager (EEM) to detect and handle critical events on Cisco NX-OS devices.

Image

The EEM monitors events that occur on the device and takes action to recover or troubleshoot these events based on the configuration.

The EEM consists of three major components:

Event statements: Events to monitor from another Cisco NX-OS component that may require some action, workaround, or notification.

Action statements: Actions that the EEM can take, such as sending an email or disabling an interface, to recover from an event.

Policies: Events paired with one or more actions to troubleshoot or recover from the event.

Policies

An EEM policy consists of an event statement and one or more action statements. The event statement defines the event to look for as well as the filtering characteristics for the event. The action statement defines the action EEM takes when the event occurs.

Figure 15-1 shows the two basic statements in an EEM policy.

Image

Images

Figure 15-1 EEM Policy Statements

EEM policies can be configured using the command-line interface (CLI) or a VSH script.

The EEM gives a device-wide view of policy management. EEM policies are configured on the supervisor, and the EEM pushes the policy to the correct module based on the event type. The EEM takes any actions for a triggered event either locally on the module or on the supervisor (the default option). The EEM maintains event logs on the supervisor.

Cisco NX-OS has a number of preconfigured system policies. These system policies define many common events and actions for the device. System policy names begin with two underscore characters (__). You can create user policies to suit your network. If you create a user policy, any actions in your policy occur after EEM triggers any system policy actions related to the same event as your policy. You can also override some system policies. The overrides that you configure take the place of the system policy. You can override the event or the actions.

Use the show event manager system-policy command to view the preconfigured system policies and determine which policies that you can override.

Table 15-2 provides some examples of system policies.

Image

Table 15-2 System Policies

Images

Event Statements

An event is any device activity for which some action, such as a workaround or a notification, should be taken. In many cases, these events are related to faults in the device such as when an interface or a fan malfunctions.

The EEM defines event filters so only critical events or multiple occurrences of an event within a specified time period trigger an associated action. Event statements specify the event that triggers a policy to run. You can configure multiple event triggers. The EEM schedules and runs policies on the basis of event statements. The EEM examines the event and action commands and runs them as defined. If you want to allow the triggered event to process any default actions, you must configure the EEM policy to allow the event default action statement.

Table 15-3 describes some of the EEM events you can use on the device.

Image

Table 15-3 EEM Events

Images

Action Statements

Action statements describe the action triggered by a policy. Each policy can have multiple action statements. If no action is associated with a policy, EEM still observes events but takes no actions.

Image

EEM supports the following actions in action statements:

• Execute any CLI commands.

• Update a counter.

• Log an exception.

• Force the shutdown of any module.

• Reload the device.

• Shut down specified modules because the power is over budget.

• Generate a syslog message.

• Generate a Call Home event.

• Generate an SNMP notification.

• Use the default action for the system policy.

If you want to allow the triggered event to process any default actions, you must configure the EEM policy to allow the default action. For example, if you match a CLI command in a match statement, you must add the event-default action statement to the EEM policy; otherwise, EEM will not allow the CLI command to execute.

Verify that your action statements within your user policy or overriding policy do not negate each other or adversely affect the associated system policy.


Note

The username: admin (with network-admin or vdc-admin user privileges) is required to configure EEM on a nondefault VDC.


Configuring EEM

Image

EEM configuration is a three-step process:

Step 1. Register the applet with the EEM and enter applet configuration mode.

event manager applet applet-name

Step 2. Configure the event statement for the policy. Repeat this step for multiple event statements.

event event-statement

Step 3. Configure an action statement for the policy. Repeat this step for multiple action statements.

action number[.number2] action-statement

You can define environment variables for EEM that are available for all policies. Environment variables are useful for configuring common values that you can use in multiple policies. For example, you can create an environment variable for the IP address of an external email server:

event manager environment variable-name variable-value

The variable-name can be any case-sensitive alphanumeric string up to 29 characters. The variable-value can be any quoted alphanumeric string up to 39 characters.

You can also override a system policy using the following command:

event manager applet applet-name override system-policy

The applet-name can be any case-sensitive alphanumeric string up to 29 characters. The system-policy must be one of the existing system policies.

Example 15-1 shows how to monitor a module powerdown.

Example 15-1 EEM Script for Monitoring Module Powerdown

switch# configure terminal
Enter configuration commands, one per line. End with CNTL/Z.
switch(config)# event manager applet monitorPoweroff
switch(config-applet)#
switch(config-applet)# description “Monitors module power down.”
switch(config-applet)# event cli match “conf t ; poweroff *”
switch(config-applet)# action 1.0 cli show module

Verifying the EEM Configuration

Image

You can use the following commands to verify the EEM configuration:

show running-config eem: Displays information about the running configuration for EEM.

show event manager system-policy [all ]: Displays information about the predefined system policies.

show event manager policy active detailed: Displays the EEM policies that are executing.

Scheduler

In regular day-to-day network operations, you need to perform multiple routine maintenance activities on a regular basis—for example, backing up data or saving a configuration. You can achieve these goals by using the Scheduler. The Scheduler uses jobs that consist of a single command or multiple commands that define routine activities. Jobs can be scheduled one time or at periodic intervals.

Image

The Scheduler defines a job and its timetable as follows:

Job: A routine task defined as a command list and completed according to a specified schedule.

Schedule: The timetable for completing a job. You can assign multiple jobs to a schedule. A schedule is defined as either periodic or one-time only.

Periodic mode: A recurring interval that continues until you delete the job. You can configure the following types of intervals:

Daily: A job is completed once a day.

Weekly: A job is completed once a week.

Monthly: A job is completed once a month.

Delta: A job begins at the specified start time and then at specified intervals (days:hours:minutes).

One-time mode: A job is completed only once at a specified time.

Before starting a job, the Scheduler authenticates the user who created the job. Because user credentials from a remote authentication are not retained long enough to support a scheduled job, you need to locally configure the authentication passwords for users who create jobs. These passwords are part of the Scheduler configuration and are not considered a locally configured user. Before starting the job, the Scheduler validates the local password against the password from the remote authentication server.

The Scheduler maintains a log file containing the job output. If the size of the job output is greater than the size of the log file, the output is truncated.


Note

The Scheduler requires no license.


The Scheduler has the following prerequisites:

• You must enable any conditional features before you can configure those features in a job.

• You must have a valid license installed for any licensed features that you want to configure in the job.

• You must have network-admin user privileges to configure a scheduled job.

Configuring Scheduler

The Scheduler has the following configuration guidelines and limitations:

• The Scheduler can fail if it encounters one of the following while performing a job:

• If the license has expired for a feature at the time the job for that feature is scheduled.

• If a feature is disabled at the time when a job for that feature is scheduled.

• If you have removed a module from a slot and a job for that slot is scheduled.

• Verify that you have configured the time. The Scheduler does not apply a default timetable. If you create a schedule and assign jobs and do not configure the time, the job is not started.

• While defining a job, verify that no interactive or disruptive commands (for example, copy bootflash: file ftp: URI, write erase, and other similar commands) are specified because the job is started and conducted noninteractively.

You can enable the Scheduler feature so that you can configure and schedule jobs, or you can disable the Scheduler feature after it has been enabled:

switch(config)# [no] feature scheduler

You can configure the log file size for capturing jobs, schedules, and job output:

switch(config)# scheduler logfile size value

In this command, value defines the scheduler log file size in kilobytes. The range is from 16 to 1024. The default is 16.


Note

If the size of the job output is greater than the size of the log file, the output is truncated.


You can configure the scheduler to use remote authentication for users who want to configure and schedule jobs. The following command configures a cleartext password for the user who is currently logged in:

switch(config)# scheduler aaa-authentication password [0 | 7] password

The following command configures a cleartext password for a remote user:

switch(config)# scheduler aaa-authentication username name password [0 | 7] password


Note

Remote users must authenticate with their cleartext password before creating and configuring jobs.


You can define a job including the job name and the command sequence. The following two commands create a job and define the sequence of commands for the specified job:

switch(config)# scheduler job name string
switch(config-job)# command1 ;[command2;command3 ;...]

You can define a timetable in the Scheduler to be used with one or more jobs. If you do not specify the time for the time commands, the Scheduler assumes the current time. You can start a job daily at a designated time specified as HH:MM. You can also start a job on a specified day of the week specified as follows:

• An integer such as 1 = Sunday, 2 = Monday, and so on.

• An abbreviation such as Sun = Sunday.

You can also start a job on a specified day each month (dm). If you specify either 29, 30, or 31, the job is started on the last day of each month.

switch(config)# scheduler schedule name string
switch(config-schedule)# job name string
switch(config-schedule)# time daily time

OR

switch(config-schedule)# time weekly[[dm:]HH:]MM

OR

switch(config-schedule)# time monthly [[dm:]HH:]MM

You can clear the Scheduler log file using the clear scheduler logfile command.

Example 15-2 shows how to create a Scheduler job that saves the running configuration to a file in bootflash and then copies the file from bootflash to a TFTP server (the filename is created using the current timestamp and switch name).

Image

Example 15-2 Scheduler Job to Back Up Configuration

switch# configure terminal
switch(config)# scheduler job name backup-cfg
switch(config-job)# cli var name timestamp $(TIMESTAMP) ;copy running-config bootflash:/$(SWITCHNAME)-cfg.$(timestamp) ;copy bootflash:/$(SWITCHNAME)-cfg.$(timestamp) tftp://1.2.3.4/ vrf management
switch(config-job)# end
switch(config)#

Example 15-3 shows how to schedule a Scheduler job called backup-cfg to run daily at 1 a.m.

Image

Example 15-3 Scheduler Job to Back Up Configuration at Specified Time

switch# configure terminal
switch(config)# scheduler schedule name daily
switch(config-if)# job name backup-cfg
switch(config-if)# time daily 1:00
switch(config-if)# end
switch(config)#

Verifying Scheduler Configuration

You can verify the Scheduler configuration using the commands shown in Table 15-4.

Image

Table 15-4 Scheduler Verification Commands

Images

Example 15-4 shows how to display the job schedule and the results of Scheduler jobs that have been executed by the Scheduler.

Example 15-4 Displaying Job Schedule and the Result of Scheduler Jobs

switch# show scheduler schedule
Schedule Name : daily
---------------------------
User Name : admin
Schedule Type : Run every day at 1 Hrs 00 Mins
Last Execution Time : Fri Jan 2 1:00:00 2019
Last Completion Time: Fri Jan 2 1:00:01 2019
Execution count : 2
-----------------------------------------------
Job Name Last Execution Status
-----------------------------------------------
back-cfg Success (0)
switch#

switch# show scheduler logfile
Job Name : back-cfg Job Status: Failed (1)
Schedule Name : daily User Name : admin
Completion time: Fri Jan 1 1:00:01 2019
--------------------------------- Job Output ---------------------------------
`cli var name timestamp 2019-01-01-01.00.00`
`copy running-config bootflash:/$(HOSTNAME)-cfg.$(timestamp)`
`copy bootflash:/switch-cfg.2019-01-01-01.00.00 tftp://1.2.3.4/ vrf management `
copy: cannot access file ‘/bootflash/switch-cfg.2019-01-01-01.00.00’
==============================================================================
Job Name : back-cfg Job Status: Success (0)
Schedule Name : daily User Name : admin
Completion time: Fri Jan 2 1:00:01 2019
--------------------------------- Job Output ---------------------------------
`cli var name timestamp 2019-01-02-01.00.00`
`copy running-config bootflash:/switch-cfg.2019-01-02-01.00.00`
`copy bootflash:/switch-cfg.2019--01-02-01.00.00 tftp://1.2.3.4/ vrf management `
Connection to Server Established.
[ ] 0.50KBTrying to connect to tftp server......
[###### ] 24.50KB
TFTP put operation was successful
==============================================================================
switch#

Bash Shell for Cisco NX-OS

In addition to the NX-OS CLI, Cisco Nexus 9000, 3000, 3500, 3600, 7000, and 7700 Series switches support access to the Bourne Again SHell (Bash). Bash interprets commands that you enter or commands that are read from a shell script. Using Bash enables access to the underlying Linux system on the device and to manage the system.

In Cisco NX-OS, Bash is accessible from user accounts that are associated with the Cisco NX-OS dev-ops role or the Cisco NX-OS network-admin role.

Example 15-5 shows the authority of the dev-ops role and the network-admin role.

Example 15-5 Displaying Authority of the dev-ops and network-admin Roles

switch# show role name dev-ops

Role: dev-ops
  Description: Predefined system role for devops access. This role
  cannot be modified.
  Vlan policy: permit (default)
  Interface policy: permit (default)
  Vrf policy: permit (default)
  -------------------------------------------------------------------
  Rule    Perm    Type        Scope               Entity
  -------------------------------------------------------------------
  4       permit  command                         conf t ; username *
  3       permit  command                         bcm module *
  2       permit  command                         run bash *
  1       permit  command                         python *

switch# show role name network-admin

Role: network-admin
  Description: Predefined network admin role has access to all commands
  on the switch
  -------------------------------------------------------------------
  Rule    Perm    Type        Scope               Entity
  -------------------------------------------------------------------
  1       permit  read-write
switch#

You can enable Bash by running the feature bash-shell command. The run bash command loads Bash and begins at the home directory for the user.

Example 15-6 shows how to enable the Bash shell feature and how to run Bash.

Image

Example 15-6 Enabling bash-shell and Running Bash

switch# configure terminal
switch(config)# feature bash-shell
switch# run bash
bash-4.2$ whoami
admin
bash-4.2$ pwd
/bootflash/home/admin
bash-4.2$

You can also execute Bash commands by using the run bash command. For instance, you can run whoami using the run bash command:

run bash whoami

You can also run Bash by configuring the user shelltype:

username foo shelltype bash

This command puts you directly into the Bash shell upon login. This does not require feature bash-shell to be enabled. You can also run NX-OS CLI commands from the Bash shell using the vsh -c command.

Managing Feature RPMs

Features on the Nexus 9000, 3000, and 3500 Series are distributed as packages. You can use the Bash shell to manage those packages. Before installing the RPM package, you need to verify the system readiness for the same by using the following command:

switch# show logging logfile | grep -i “System ready”
2018 Mar 27 17:24:22 switch %ASCII-CFG-2-CONF_CONTROL: System ready

If you see “System ready” output, you are all set.

Table 15-5 provides some of the commands that you can use to manage RPM packages using Bash.

Image

Table 15-5 Commands to Manage RPM Packages Using Bash

Images

Managing Patch RPMs

Table 15-6 shows some of the commands that you can use to manage Patch RPMs using Bash.

Image

Table 15-6 Commands to Manage Patch RPMs Using Bash

Images

Guest Shell for Cisco NX-OS

In addition to the NX-OS CLI and Bash access on the underlying Linux environment, the Cisco Nexus 9000 Series devices support access to a decoupled execution space running within a Linux Container (LXC) called the Guest Shell. When running in the Guest Shell, you have network-admin privileges.

From within the Guest Shell, the network-admin has the following capabilities:

• Access to the network over Linux network interfaces

• Access to Cisco Nexus switch bootflash

• Access to Cisco Nexus switch volatile tmpfs

• Access to Cisco Nexus switch CLI

• Access to Cisco NX-API REST

• The ability to install and run Python scripts

• The ability to install and run 32-bit and 64-bit Linux applications

Decoupling the execution space from the native host system allows customization of the Linux environment to suit the needs of the applications without impacting the host system or applications running in other Linux Containers.

Accessing the Guest Shell

Image

You can use the run guestshell CLI command to access the Guest Shell on the Cisco Nexus device; the run guestshell command parallels the run bash command that is used to access the host shell. This command allows you to access the Guest Shell and get a Bash prompt or run a command within the context of the Guest Shell. The command uses password-less SSH to an available port on the localhost in the default network namespace.

The Cisco NX-OS automatically installs and enables the Guest Shell by default on systems with sufficient resources. Subsequent upgrades to the Cisco Nexus series switch software will not automatically upgrade the Guest Shell. The Guest Shell is based on a CentOS 7 root file system.


Note

Systems with 4 GB of RAM will not enable the Guest Shell by default. The Guest Shell is automatically enabled on systems with more than 4 GB of RAM.


The Guest Shell starts an OpenSSH server upon bootup. The server listens on a randomly generated port on the localhost IP address interface 127.0.0.1 only. This provides the password-less connectivity into the Guest Shell from the NX-OS virtual-shell when the guestshell keyword is entered. If this server is killed or its configuration (residing in /etc/ssh/sshd_config-cisco) is altered, access to the Guest Shell from the NX-OS CLI might not work.

Starting in 2.2(0.2), the Guest Shell will dynamically create user accounts with the same username with which the user logged in to the switch. However, all other information is NOT shared between the switch and the Guest Shell user accounts.

In addition, the Guest Shell accounts are not automatically removed, so they must be removed by the network administrator when no longer needed.

Resources Used for the Guest Shell

By default, the resources for the Guest Shell have a small impact on resources available for normal switch operations. If the network-admin requires additional resources for the Guest Shell, the guestshell resize{cpu | memory | rootfs} command changes these limits.

Table 15-7 shows the Guest Shell resource limits.

Table 15-7 Guest Shell Resource Limits

Images

The CPU limit is the percentage of the system compute capacity that tasks running within the Guest Shell are given when there is contention with other compute loads in the system. When there is no contention for CPU resources, the tasks within the Guest Shell are not limited.


Note

A Guest Shell reboot is required after changing the resource allocations. This can be accomplished with the guestshell reboot command.


Misbehaving or malicious application code can cause DoS as the result of overconsumption of connection bandwidth, disk space, memory, and other resources. The host provides resource-management features that ensure fair allocation of resources between the Guest Shell and services on the host.

Capabilities in the Guest Shell

The Guest Shell is populated with CentOS 7 Linux, which provides the ability to Yum install software packages built for this distribution. The Guest Shell is prepopulated with many of the common tools that would naturally be expected on a networking device, including net-tools, iproute, tcpdump, and OpenSSH. Python 2.7.5 is included by default, as is the PIP for installing additional Python packages.

Image

The Guest Shell has access to the Linux network interfaces used to represent the management and data ports of the switch. Typical Linux methods and utilities like ifconfig and ethtool can be used to collect counters, as shown in Example 15-7. When an interface is placed into a Virtual Routing and Forwarding (VRF) in the NX-OS CLI, the Linux network interface is placed into a network namespace for that VRF. You can see the name spaces at /var/run/netns and can use the ip netns utility to run in the context of different namespaces. A couple of utilities, chvrf and vrfinfo, are provided as a convenience for running in a different namespace and getting information about which namespace or VRF a process is running in.

Example 15-7 Displaying Counters for Ethernet 1/47 Interface Inside Guest Shell

switch# guestshell
[guestshell@guestshell ~]$ ifconfig Eth1-47
Eth1-47: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 13.0.0.47 netmask 255.255.255.0 broadcast 13.0.0.255
ether 54:7f:ee:8e:27:bc txqueuelen 100 (Ethernet)
RX packets 311442 bytes 21703008 (20.6 MiB)
RX errors 0 dropped 185 overruns 0 frame 0
TX packets 12967 bytes 3023575 (2.8 MiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

The Guest Shell provides an application to allow the user to issue NX-OS commands from the Guest Shell environment to the host network element. The dohost application accepts any valid NX-OS configuration or exec commands and issues them to the host network element.

When you are invoking the dohost command, each NX-OS command may be in single or double quotes:

dohost "<NXOS CLI>"

Example 15-8 shows how to use the dohost command.

Example 15-8 Using the dohost Command

[guestshell@guestshell ~]$ dohost “sh lldp time | in Hold” “show cdp global”
Holdtime in seconds: 120
Global CDP information:
CDP enabled globally
Refresh time is 21 seconds
Hold time is 180 seconds
CDPv2 advertisements is enabled
DeviceID TLV in System-Name(Default) Format
[guestshell@guestshell ~]$

Python can be used interactively, or Python scripts can be run in the Guest Shell, as shown in Example 15-9.

Example 15-9 Running Python Inside the Guest Shell

guestshell:~$ python
Python 2.7.5 (default, Jun 24 2019, 00:41:19)
[GCC 4.8.3 20140911 (Red Hat 4.8.3-9)] on linux2
Type “help”, “copyright”, “credits” or “license” for more information.
>>>
guestshell:~$

The Pip Python Package Manager is included in the Guest Shell to allow the network-admin to install new Python packages, as shown in Example 15-10.

Example 15-10 Using Pip Python Package Manager to Install a Python Package

[guestshell@guestshell ~]$ sudo su
[root@guestshell guestshell]# pip install Markdown
Collecting Markdown
Downloading Markdown-2.6.2-py2.py3-none-any.whl (157kB)
100% |################################| 159kB 1.8MB/s
Installing collected packages: Markdown
Successfully installed Markdown-2.6.2
[root@guestshell guestshell]# pip list | grep Markdown
Markdown (2.6.2)
[root@guestshell guestshell]#

To preserve the integrity of the files within the Guest Shell, the file systems of the Guest Shell are not accessible from the NX-OS CLI. For the host, bootflash: and volatile: are mounted as /bootflash and /volatile within the Guest Shell. A network-admin can access files on this media using the NX-OS exec commands from the host or using Linux commands from within the Guest Shell.

Managing the Guest Shell

Table 15-8 lists commands to manage the Guest Shell.

Image

Table 15-8 Commands to Manage the Guest Shell

Images

The guestshell disable command shuts down and disables the Guest Shell, as shown in Example 15-11.

Example 15-11 Using the guestshell disable Command

switch# guestshell disable
You will not be able to access your guest shell if it is disabled. Are you sure you want to disable the guest shell? (y/n) [n) y
2019 Jul 30 19:47:23 switch %$ VDC-1 %$ %VMAN-2-ACTIVATION_STATE: Deactivating virtual service ‘guestshell+’
2019 Jul 30 18:47:29 switch %$ VDC-1 %$ %VMAN-2-ACTIVATION_STATE: Successfully deactivated virtual service ‘guestshell+’

The guestshell destroy command uninstalls the Guest Shell and its artifacts, as shown in Example 15-12.

Example 15-12 Using the guestshell destroy Command

switch# guestshell destroy
You are about to destroy the guest shell and all of its contents. Be sure to save your work. Are you sure you want to continue? (y/n) [n] y
2019 Jul 30 18:49:10 switch %$ VDC-1 %$ %VMAN-2-INSTALL_STATE: Destroying virtual service
 ‘guestshell+’
2019 Jul 30 18:49:10 switch %$ VDC-1 %$ %VMAN-2-INSTALL_STATE: Successfully destroyed
virtual service ‘guestshell +’

The guestshell enable command installs the Guest Shell from a Guest Shell software package, as shown in Example 15-13. By default, the package embedded in the system image is used for the installation. The command is also used to reactivate the Guest Shell if it has been disabled.

Example 15-13 Using the guestshell enable Command

switch# guestshell enable
2019 Jul 30 18:50:27 switch %$ VDC-1 %$ %VMAN-2-INSTALL_STATE: Installing virtual service ‘guestshell+’
2019 Jul 30 18;50;42 switch %$ VDC-1 %$ %VMAN-2-INSTALL_STATE: Install success virtual service ‘guestshell+’; Activating
2019 Jul 30 18:50:42 switch %$ VDC-1 %$ %VMAN-2-ACTIVATION_STATE: Activating virtual service ‘guestshell+’
2019 Jul 30 18:51:16 switch %$ VDC-1 %$ %VMAN-2-ACTIVATION_STATE: Successfully activated
virtual service ‘guestshell+’

The output of the show guestshell detail command displays details about the guestshell package (such as version, signing resources, and devices), as shown in Example 15-14.

Example 15-14 Using the guestshell detail Command

switch# show guestshell detail
Virtual service guestshell+ detail
  State                 : Activated
  Package information
    Name                : guestshell.ova
    Path                : /isan/bin/guestshell.ova
    Application
      Name              : GuestShell
      Installed version : 2.2(0.2)
      Description       : Cisco Systems Guest Shell
    Signing
      Key type          : Cisco key
      Method            : SHA-1
    Licensing
      Name              : None
      Version           : None
  Resource reservation
    Disk                : 250 MB
    Memory              : 256 MB
    CPU                 : 1% system CPU

  Attached devices
    Type              Name        Alias
    ---------------------------------------------
    Disk              _rootfs
    Disk              /cisco/core
    Serial/shell
    Serial/aux
    Serial/Syslog                 serial2
    Serial/Trace                  serial3

XML

Extensible Markup Language (XML) is a markup language that defines a set of rules for encoding documents in a format that is both human-readable and machine-readable. XML follows a specific format and helps give structure to data. Because XML is platform-neutral, computer-language-neutral, and text-based, it is useful for data exchange between computers and for data storage.

Example 15-15 displays a fragment from an XML document that shows how you might structure some simple data about a network device.

Image

Example 15-15 XML Structure of a Network Device

<device>
         <interface>mgmt0</interface>
         <state>up</state>
         <eth_ip_addr>192.168.10.175</eth_ip_addr>
         <eth_ip_mask>24</eth_ip_mask>
<device>

The XML fragment has a root element called device. The device element has four child elements:

• interface

• state

• eth_ip_addr

• eth_ip_mask

You can think of each element as a data field. XML provides structure to those data fields. XML doesn’t do anything with the data. To manipulate that data, a piece of software has to send, receive, store, or display it. One example of such software is Google Postman.

Example

Example 15-16 displays an XML document that has a root node element called ciscopress. Notice that the ciscopress element contains one child element: book.

Example 15-16 XML Structure Example

<?xml version =“1.0” encoding=“UTF-8”?>
  <ciscopress>
    <book isbn=“1587052024”>
      <title>Routing TCP/IP</title>
      <author>Jeff Doyle</author>
      <category></category>
      <year>2005</year>
      <edition>2</edition>
      <price>72</price>
    </book>
  </ciscopress>

Figure 15-2 shows a visual representation of the sample XML document as a tree.

Images

Figure 15-2 Visual Representation of XML Document as a Tree

Note the following points:

• The book element contains multiple child elements.

• The book element contains metadata in the form of an attribute called isbn. An element can contain multiple attributes.

• The <category> element in the sample XML document contains no character data. It’s an “empty element.” This is valid if the underlying schema allows it.

One aspect of the XML language that sets it apart from a markup language like HTML is that it has no predefined tags. The elements in Figure 15-2, such as <ciscopress> and <price>, are not defined in the XML standard. These elements and the document structure are created by the author of the XML document. That’s different from the way HTML works with predefined tags such as <p>, <h1>, and <table>.

An XML document that contains data is also sometimes referred to as an XML payload.

XML Syntax

Image

The basic unit of an XML document is called an element. Each XML element must conform to the following rules to be considered “well formed”:

• Each XML element must have a start-tag and an end-tag. The tags are enclosed in angle brackets—for example, <device>…</device>. Unlike HTML, the closing tag is mandatory.

• An empty-element tag (or standalone tag) must be properly closed—for example, <interface></interface>.

• An XML element includes its start-tag, enclosing character data and/or child elements, and the end-tag.

• The element’s name can contain letters, numbers, and other Unicode characters, but NOT white spaces.

• The element’s name must start with a letter, an underscore “_”, or a colon “:”, but cannot start with certain reserved words such as xml.

• Each XML document must have one (and only one) root element. XML elements must be properly nested. For example,<device><interface>… </device></interface is incorrectly nested. The correct nesting is <device><interface>…</interface></device>.

• XML is case sensitive. For example,<Interface> and <interface> are considered two different elements.

• The start-tag may contain attributes in the form of attribute_name=“attribute_value”. Attributes are used to provide extra information about the element. Unlike HTML, the attribute_value of an XML attribute must be properly quoted (either in double quotes or single quotes).

• Certain characters, such as <, >, which are used in XML syntax, must be replaced with entity references in the form of &entity_name;. XML has five predefined entity references:

• &lt; (<)

• &gt; (>)

• &amp; (&)

• &quot; (“)

• &apos; (‘).

• XML comments can be used in the form <!-- comment texts -->, which is the same as HTML.

• Unlike HTML, white spaces in the text are preserved.

• A new-line character is represented by a Line Feed (LF) character (0AH).

JSON

Image

JavaScript Object Notation (JSON) is a lightweight text-based open standard designed for human-readable data interchange.

JSON objects contain data in a consistent format that can be passed and programmatically consumed more easily than the data in report formats. A JSON object is an unordered set of name/value pairs, so it tends to be self-explanatory, like XML, but it is less bulky.

Parameters for JSON objects are passed in the following format: ParameterName:parameterValue. A proper JSON object begins with a left brace { and ends with a right brace }. Each name in a pair is followed by a colon (:) and then the corresponding value. The name/value pairs are separated by commas.

Example 15-17 displays a fragment from a JSON document that shows how you might structure some simple data about a network device.

Image

Example 15-17 JSON Structure of a Network Device

{
    “device”: {
      “interface”: “mgmt0”,
       “state”: “up”,
       “eth_ip_addr”: “192.168.10.175”,
       “eth_ip_mask”: 24,
                }
}

Image

Both JSON and XML are human-readable formats. They are both independent of any specific programming language. However, there are a few differences:

Verbose: XML is more verbose than JSON and usually uses more characters to express the same data than JSON.

Arrays: XML is used to describe structured data, which doesn’t include arrays, whereas JSON includes arrays.

Parsing: Although most programming languages contain libraries that can parse both JSON and XML data, evaluating specific data elements can be more difficult in XML (although more powerful) compared to JSON.

Rest API

Image

An application programming interface (API) is a way for two pieces of software to talk to each other. An API allows for the development of rich applications with a wide variety of functionality. Let’s go through an example.

Suppose you are the creator of an online marketplace named Jack’s Shop, where people can come and buy stuff and get it delivered to their home/office. How do you track which user purchased what? You need to maintain a database with user accounts and user order history. But you don’t want to maintain a user credentials database in-house. You would like your users to log in using their Google or Facebook accounts. How do you achieve this? A simple answer to this question would be using the Facebook API or Google API to authenticate users.

REST is centered around the HTTP request and response model. Consuming an API is just as simple as making an HTTP request. For example, if you make a request to an API Service, the result of the request will be returned in the response. The data returned in the response is usually JSON or XML.

Image

To construct a request, you need to know the following information for the API that you are calling. You can find this information in the API reference documentation.

Method

• GET: Retrieve data.

• POST: Create something new.

• PUT: Update data.

• DELETE: Delete data.

URL

• The URL for the endpoint you want to call.

• Example: http://apic/api/aaaLogin.xml

URL Parameters

• The parameters that you can pass as part of the URL.

Authentication

• Authentication type (Basic HTTP, token-based, and OAuth are common).

• Authentication credentials.

Additional HTTP Headers

• Additional HTTP headers required by the specific API.

• Example: Content-Type: application/json

Request Body

• JSON or XML containing the HTTP Message Body data bytes that are needed to complete the request.

Response Body

• JSON or XML containing the HTTP Message Body data bytes transmitted in an HTTP transaction message response.

Figure 15-3 shows the REST API request and response process.

Images

Figure 15-3 REST API Request and Response

Authentication

There are different types of authentication for REST APIs. Authentication is used to control access and access rights to the REST APIs. For example, some users might have read-only access, which means that they can use only the parts of the API that read data. Other users might have both read and write access. This means they can use the API to perform operations that not only read data but also add, edit, and delete data. These access rights are typically based on user-assigned roles such as Administrator that would have full rights to change data, whereas a plain User role might have read-only access rights.

The following list shows the types of authentication controls.

None: The Web API resource is public; anybody can place a call. Generally, the case for GET methods, rarely for POST, PUT, DELETE.

Basic HTTP: The username and password are passed to the server in an encoded string.

• Authorization: Basic ENCODEDSTRING

Token: A secret key generally retrieved from the Web API developer portal.

• The keyword may change from one Web API to another: Bearer, token.

• Passed with each API call.

OAuth: A sequence flow is initiated to retrieve an access token from an identity provider. The token is then passed with each API call.

• Open standard. User rights are associated with the token (OAuth scope).

• The token expires. It can be revoked. It can also be reissued via a refresh token.

Response

Image

The returned data is defined in the Response portion, which includes the HTTP status codes along with the data format and attributes.

• HTTP status codes

• HTTP status codes are used to return success, error, or other statuses. (See http://www.w3.org/Protocols/HTTP/HTRESP.html.)

• Some common examples are

• 200 OK

• 202 Accepted/Processing

• 401 Not Authorized

• Content

• Often returned in different formats based on the request. Common formats are JSON, XML, and Text.

Figure 15-4 shows a REST API request and response all in the same window using Postman.

Images

Figure 15-4 REST API Request and Response Using Postman

NX-API

CLI commands are mostly run on the Nexus devices. NX-API enables you to access these CLIs by making them available outside the switch by using HTTP/HTTPS. You can use this extension to the existing Cisco Nexus CLI system on the Cisco Nexus 9000, 3000, 3500, 3600, and 7000 Series devices. NX-API supports show commands, configurations, and Linux Bash. NX-API uses HTTP/HTTPS as its transport. CLIs are encoded into the HTTP/HTTPS POST body.

The NX-API back end uses the Nginx HTTP server. The Nginx process, and all of its children processes, are under Linux cgroup protection where the CPU and memory usage are capped. If the Nginx memory usage exceeds the cgroup limitations, the Nginx process is restarted and restored.

NX-API is integrated into the authentication system on the device. Users must have appropriate accounts to access the device through NX-API. NX-API uses HTTP basic authentication. All requests must contain the username and password in the HTTP header. You should consider using HTTPS to secure your user’s login credentials.

NX-API provides a session-based cookie, nxapi_auth, when users first successfully authenticate. With the session cookie, the username and password are included in all subsequent NX-API requests that are sent to the device. The username and password are used with the session cookie to bypass performing the full authentication process again. If the session cookie is not included with subsequent requests, another session cookie is required and is provided by the authentication process. Avoiding unnecessary use of the authentication process helps reduce the workload on the device.


Note

A nxapi_auth cookie expires in 600 seconds (10 minutes). This value is a fixed and cannot be adjusted.


The commands, command type, and output type for the Cisco Nexus 9000 Series devices are entered using NX-API by encoding the CLIs into the body of an HTTP/HTTPS POST. The response to the request is returned in XML or JSON output format.

NX-API CLI is enabled by default for local access. The remote HTTP access is disabled by default. First, you need to enable the NX-API feature before you can send any API requests to the NX-OS software.

To enable the NX-API nxapi feature, enter these commands:

switch# conf t
switch(config)# feature nxapi

Example 15-18 shows a request and its response in XML format.

Example 15-18 Request and Response in XML Format

Request:
<?xml version=“1.0”?>
<ins_api>
  <version>1.2</version>
  <type>cli_show</type>
  <chunk>0</chunk>
  <sid>sid</sid>
  <input>show clock</input>
  <output_format>xml</output_format>
</ins_api>

Response:
<?xml version=“1.0”?>
<ins_api>
  <type>cli_show</type>
  <version>1.2</version>
  <sid>eoc</sid>
  <outputs>
    <output>
      <body>
       <simple_time>01:30:58.810 UTC Thu May 30 2019</simple_time>
      </body>
      <input>show clock</input>
      <msg>Success</msg>
      <code>200</code>
    </output>
  </outputs>
</ins_api>

Example 15-19 shows a request and its response in JSON format.

Example 15-19 Request and Response in JSON Format

Request:
{
  “ins_api”: {
    “version”: “1.2”,
    “type”: “cli_show”,
    “chunk”: “0”,
    “sid”: “1”,
    “input”: “show clock”,
    “output_format”: “json”
  }
}
Response:
{
  “ins_api”: {
    “type”: “cli_show”,
    “version”: “1.2”,
    “sid”: “eoc”,
    “outputs”: {
      “output”: {
        “input”: “show clock”,
        “msg”: “Success”,
        “code”: “200”,
        “body”: {
          “simple_time”: “01:29:16.684 UTC Thu May 30 2019”
        }
      }
    }
  }
}

NX-API Request and Response Elements

NX-API request elements are sent to the device in XML format or JSON format. The HTTP header of the request must identify the content type of the request.

You can use the NX-API request elements shown in Table 15-9 to specify a CLI command for XML or JSON format.

Image

Table 15-9 NX-API Request Elements

Images

The NX-API elements that respond to a CLI command are listed in Table 15-10.

Image

Table 15-10 NX-API Response Element

Images

Table 15-11 provides some of the possible NX-API errors, error codes, and messages of an NX-API response.

Image

Table 15-11 NX-API Response and Error Codes

Images

NX-API Developer Sandbox

The Cisco NX-API Developer Sandbox is a web form hosted on the switch. It translates NX-OS CLI commands into equivalent XML or JSON payloads and converts NX-API REST payloads into their CLI equivalents. The web form is a single screen with three panes—Command (top pane), Request (bottom left pane), and Response (bottom right pane)—as shown in Figure 15-5.

Images

Figure 15-5 NX-API Sandbox GUI

The Request pane also has a series of tabs. Each tab represents a different language: Python, Java, and JavaScript. Each tab enables you to view the request in the respective language. For example, after converting CLI commands into an XML or JSON payload, click the Python tab to view the request in Python, which you can use to create scripts.

Controls in the Command pane enable you to choose a supported command type, such as cli_show, cli_show_ascii, cli_conf, and a message format, such as XML or JSON. The available options vary depending on the chosen method.

When you type or paste one or more CLI commands into the Command pane, the web form converts the commands into a REST API payload, checking for configuration errors, and displays the resulting payload in the Request pane. If you then choose to post the payload directly from the sandbox to the switch (by choosing the POST option), the Response pane displays the API response.

Exam Preparation Tasks

As mentioned in the section “How to Use This Book” in the Introduction, you have a couple of choices for exam preparation: the exercises here, Chapter 20, “Final Preparation,” and the exam simulation questions in the Pearson Test Prep software online.

Review All Key Topics

Review the most important topics in the chapter, noted with the key topic icon in the outer margin of the page. Table 15-12 lists a reference to these key topics and the page numbers on which each is found.

Image

Table 15-12 Key Topics for Chapter 15

Images

Memory Tables

Print a copy of Appendix C, “Memory Tables” (found on the companion website), or at least the section for this chapter, and complete the tables and lists from memory. Appendix D, “Memory Tables Answer Key,” also on the companion website, includes completed tables and lists to check your work.

Define Key Terms

Define the following key terms from this chapter, and check your answers in the Glossary.

Embedded Event Manager (EEM)

event statements

action statements

policies

Scheduler

job

schedule

Bourne Again SHell (Bash Shell)

Yellowdog Updater Modified (YUM)

RPM Package Manager (RPM)

Guest Shell

Extensible Markup Language (XML)

JavaScript Object Notation (JSON)

application programming interface (API)

RESTful API (REST API)

NX-API

NX-API Developer Sandbox

References

Cisco Nexus 7000 Series NX-OS System Management Configuration Guide 8.x: https://www.cisco.com/c/en/us/td/docs/switches/datacenter/nexus7000/sw/system-management/config/cisco_nexus7000_system-management_config_guide_8x.html

Cisco Nexus 9000 Series NX-OS System Management Configuration Guide, Release 9.2(x): https://www.cisco.com/c/en/us/td/docs/switches/datacenter/nexus9000/sw/92x/system-management/b-cisco-nexus-9000-series-nx-os-system-management-configuration-guide-92x/b-cisco-nexus-9000-series-nx-os-system-management-configuration-guide-92x_chapter_01001.html

Cisco Nexus 9000 Series NX-OS Programmability Guide, Release 9.2(x): https://www.cisco.com/c/en/us/td/docs/switches/datacenter/nexus9000/sw/92x/programmability/guide/b-cisco-nexus-9000-series-nx-os-programmability-guide-92x.html

Cisco DevNet: https://developer.cisco.com/

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.224.44.100