7 Network Programmability Concepts
7 Network Programmability Concepts
COM/C/NETWORKJOURNEY
TOPICS COVERED:
NETWORK PROGRAMMABILITY
APIs are mechanisms used to communicate with applications and other software.
They are also used to communicate with various components of the network through software.
There are multiple different types of APIs. However, the focus is on two of the most common APIs:
the Northbound and Southbound APIs.
Northbound API
Northbound APIs are often used to communicate from a network controller to its management
software. For example, Cisco DNA Center has a software graphical user interface (GUI) that is used to
manage the network controller. Typically, when a network operator logs into a controller to manage
the network, the information that is being passed from the management software is leveraging a
Northbound REST-based API. Best practices suggest that the traffic should be encrypted using TLS
between the software and the controller. Most types of APIs have the ability to use encryption to
secure the data in flight.
Southbound API
If a network operator makes a change to a switch’s configuration in the management software of the
controller, those changes are then pushed down to the individual devices by using a Southbound API.
These devices can be routers, switches, or even wireless access points. APIs interact with the
components of a network through the use of a programmatic interface.
HTTP functions are similar to the functions that most applications or databases use to store or alter
data—whether the data is stored in a database or within the application. These functions are called
“CRUD” functions.
CRUD is an acronym that stands for CREATE, READ, UPDATE, and DELETE. For example, in a SQL
database, the CRUD functions are used to interact with or manipulate the data stored in the
database.
Introduction to Postman
It also discussed being able to test code to see if the desired outcomes are accomplished when
executing the code.
Keep in mind that APIs are software interfaces into an application or a controller.
This means that such an API is considered just like any other device to which a user needs to
authenticate to gain access to utilize the APIs.
A developer who is authenticated has access to making changes using the API, which can impact that
application.
This means if a REST API call is used to delete data, that data will be removed from the application or
controller just as if a user logged into the device via the CLI and deleted it.
It is best practice to use a test lab or the Cisco DevNet sandbox while learning or practicing any of
these concepts to avoid accidental impact to a production or lab environment.
The Postman application has various sections that you can interact with. The focus here is on using
the Builder portion of the dashboard. The following sections are the ones that require the most
focus and attention:
■ History
■ Collections
■ New Tab
■ URL bar
The History tab shows a list of all the recent API calls made using Postman. Users have the option to
clear their entire history at any time if they want to remove the complete list of API calls that have
been made. This is done by clicking the Clear All link at the top of the Collection window (see Figure
28-3). Users also have the ability to remove individual API calls from the history list by simply
hovering the mouse over an API call and clicking the trash can icon in the submenu that pops up.
API calls can be stored in groups, called collections, that are specific to a structure that fits the user’s
needs. Collections can follow any naming convention and appear as a folder hierarchy. For example,
it’s possible to have a collection called DNA-C to store all the Cisco DNA Center API calls. Saving API
calls to a collection helps during testing phases as the API calls can easily be found and sorted.
Tabs provide another very convenient way to work with various API calls. Each tab can have its own
API call and parameters that are completely independent of any other tab. For example, a user can
have one tab open with API calls interacting with the Cisco DNA Center controller and another tab
open that is interacting with a completely different platform, such as a Cisco Nexus switch. Each tab
has its own URL bar to be able to use a specific API. Remember that an API call using REST is very
much like an HTTP transaction. Each API call in a RESTful API maps to an individual URL for a
particular function. This means every configuration change or poll to retrieve data a user makes in a
REST API has a unique URL—whether it is a GET, POST, PUT, PATCH, or DELETE function
It is also important to note that the HTTP POST function is used to send the credentials to the Cisco
DNA Center controller.
Cisco DNA Center uses basic authentication to pass a username and password to the Cisco DNA
Center Token API to authenticate users.
This API is used to authenticate a user to the Cisco DNA Center controller to make additional API
calls.
Just as users do when logging in to a device via the CLI, if secured properly, they should be prompted
for login credentials.
The same method applies to using an API to authenticate to software. The key steps necessary to
successfully set up the API call in Postman are as follows:
You need a token for any future API calls to the Cisco DNA Center controller. When you are
successfully authenticated to the Cisco DNA Center controller, you receive a token that contains a
string that looks similar to the following:
"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiI1YTU4Y2QzN2UwNWJiYTAwOGVmNjJiOT
IiLCJhdXRoU291cmNlIjoiaW50ZXJuYWwiLCJ0ZW5hbnROYW1lIjoiVE5UMCIsInJvbGVzIjpbIjVhMz
E1MTYwOTA5MGZiYTY5OGIyZjViNyJdLCJ0ZW5hbnRJZCI6IjVhMzE1MTlkZTA1YmJhMDA4ZWY2
MWYwYSIsImV4cCI6MTUyMTQ5NzI2NCwidXNlcm5hbWUiOiJkZXZuZXR1c2VyIn0.tgAJfLc1OaUwa
JCX6lzfjPG7Om2x97oiTIozUpAzomM"
You can see in the top right of the screen shown in Figure 28-8 that the received HTTP status code
from the Cisco DNA Center controller is 200 OK.
You can tell that the HTTP status code 200 means that the API call completed successfully.
In addition, you can see how long it took to process the HTTP POST request: 980 ms.
Now we can take a look at some of the other available API calls. The first API call that is covered in
this section is the Network Device API, which allows users to retrieve a list of devices that are
currently in inventory that are being managed by the Cisco DNA Center controller.
Step 1. Copy the token you received earlier and click a new tab in Postman.
Step 2. In the URL bar enter https://sandboxdnac.cisco.com/api/v1/network-device to target the
Network Device API.
Step 3. Select the HTTP GET operation from the dropdown box.
Step 4. Select the Headers tab and enter Content-Type as the key.
Based on the response received from the Cisco DNA Center controller, you can see the HTTP status
code 200 OK, and you can also see that a device inventory was received, in JSON format.
Cisco SD-WAN APIs is a bit different from using the Cisco DNA Center APIs, but the two processes are
quite similar.
As when using a Cisco DNA Center API, with a Cisco SD-WAN API you need to provide login
credentials to the API in order to be able to utilize the API calls.
Some key pieces of information are necessary to successfully set up the API call in Postman:
■ The URL bar must have the API call to target the Authentication API.
■ The HTTP POST operation is used to send the username and password to Cisco vManage.
■ The Headers Content-Type key must be application/x-www-form-urlencoded.
■ The body must contain keys with the j_username devnetuser and thej_password Cisco123!.
Postman environment set up for the Cisco SD-WAN API calls—specifically, the Authentication API
If you scroll down in the response, you can see a list of devices under the “data” key received from
the API call. This list contains a series of information about each fabric device within Cisco vManage.
Some of the information you can see in Figure 28-14 is as follows:
■ Device ID
■ System IP
■ Host name
■ Reachability
■ Status
■ Device type
■ Site ID
As you can see, a single API call has the power to gather a significant amount of information.
How the data is used is up to the person making the API calls and collecting the data.
Detailed steps for setting up the Postman environment for Cisco SD-WAN are available at
https://developer.cisco.com/sdwan/
Text-file formats that can be used to store structured data that can be handy for embedded and
Web applications.
1. 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.
Example:
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications
with XML.</description>
</book>
2. JSON
JavaScript Object Notation (JSON) is used with JavaScript, of course. It will be familiar to Web
developers that use it for client/server communication.
{
"books": [
{
"id": "bk102",
"author": "Crockford, Douglas",
"title": "JavaScript: The Good Parts",
"genre": "Computer",
"price": 29.99,
"publish_date": "2008-05-01",
"description": "Unearthing the Excellence in JavaScript"
}
]
}
3. YAML
YAML stands for YAML Ain’t Markup Language. It uses line and whitespace delimiters instead of
explicitly marked blocks that could span one or more lines like XML and JSON. This approach is used
in many programming languages, such as Python.
It is commonly used for configuration files and in applications where data is being stored or
transmitted.
Example2:
books:
- id: bk102
author: Crockford, Douglas
title: 'JavaScript: The Good Parts'
genre: Computer
price: 29.99
publish_date: !!str 2008-05-01
description: Unearthing the Excellence in JavaScript
Now that the XML and JSON data formats have been explained, it is important to circle back to
actually using the REST API and the associated responses and outcomes of doing so.
First, we need to look at the HTTP response status codes. Most Internet users have experienced the
dreaded “404 Not Found” error when navigating to a website. However, many users don’t know
what this error actually means.
Data models describe the things you can configure, monitor, and the actions you can perform on a
network device.
Many network management protocols have associated data modeling languages. SNMP is widely
used for fault handling and monitoring. However, it is not often used for configuration changes. CLI
scripting is used more often than other methods. The data modeling language associated with SNMP
was called the Structure of Management Information (SMI). In the late 1990s, a project was started
to create a replacement for SMIv2, which was called SMIng, which was failed.
YANG data models are an alternative to SNMP MIBs and are becoming the standard for data
definition languages.
YANG, which is defined in RFC 6020, uses data models. Data models are used to describe whatever
can be configured on a device, everything that can be monitored on a device, and all the
administrative actions that can be executed on a device, such as resetting counters or rebooting the
device. This includes all the notifications that the device is capable of generating. All these variables
can be represented within a YANG model. Data models are very powerful in that they create a
uniform way to describe data, which can be beneficial across vendors’ platforms.
Data models allow network operators to configure, monitor, and interact with network devices
holistically across the entire enterprise environment.
YANG models use a tree structure. Within that structure, the models are similar in format to XML
and are constructed in modules. These modules are hierarchical in nature and contain all the
different data and types that make up a YANG device model. YANG models make a clear distinction
between configuration data and state information. The tree structure represents how to reach a
specific element of the model, and the elements can be either configurable or not configurable.
Every element has a defined type. For example, an interface can be configured to be on or off.
However, the operational interface state cannot be changed; for example, if the options are only up
or down, it is either up or down, and nothing else is possible.
YANG Example:
container food {
choice snack {
case sports-arena {
leaf pretzel {
type empty;
}
leaf popcorn {
type empty;
}
}
case late-night {
leaf chocolate {
type enumeration {
enum dark;
enum milk;
enum first-available;
}
}
}
}
}
2. NETCONF
NETCONF, defined in RFC 4741 and RFC 6241, is an IETF (Internet Engineering Task Force) standard
protocol that uses the YANG data models to communicate with the various devices on the network.
NETCONF runs over SSH, TLS, and (although not common), Simple Object Access Protocol (SOAP).
One of the most important differences is that SNMP can’t distinguish between configuration data
and operational data, but NETCONF can.
The following is a list of some of the common use cases for NETCONF:
■ Collecting the status of specific fields
■ Changing the configuration of specific fields
■ Taking administrative actions
■ Sending event notifications
■ Backing up and restoring configurations
■ Testing configurations before finalizing the transaction
NETCONF element from RFC 4741. This NETCONF output can be read as follows: There is an XML list
of users named users. In that list, there are individual users named Dave, Rafael, and Dirk.
<rpc-reply message-id="101"
xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
<data>
<top xmlns="http://example.com/schema/1.2/config">
<users>
<user>
<name>Dave</name>
</user>
<user>
<name>Rafael</name>
</user>
<user>
<name>Dirk</name>
</user>
</users>
</top>
</data>
</rpc-reply>
How NETCONF uses YANG data models to interact with network devices and then talk back to
management applications. The dotted lines show the devices talking back directly to the
management applications, and the solid lines illustrate the NETCONF protocol talking between the
management applications and the devices.
NETCONF exchanges information called capabilities when the TCP connection has been made.
Capabilities tell the client what the device it’s connected to can do. Furthermore, other information
can be gathered by using the common NETCONF operations.
Now that we’ve looked at the basics of NETCONF and XML, let’s examine some actual examples of a
NETCONF RPC message. Below example of an OSPF NETCONF RPC message that provides the OSPF
routing configuration of an IOS XE device.
<rpc-reply message-id="urn:uuid:0e2c04cf-9119-4e6a-8c05-238ee7f25208"
xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" xmlns:nc="urn:ietf:params:
xml:ns:netconf:base:1.0">
<data>
<native xmlns="http://cisco.com/ns/yang/ned/ios">
<router>
<ospf>
<id>100</id>
<redistribute>
<connected>
<redist-options>
<subnets/>
</redist-options>
</connected>
</redistribute>
<network>
<ip>10.10.0.0</ip>
<mask>0.0.255.255</mask>
<area>0</area>
</network>
<network>
<ip>20.20.0.0</ip>
<mask>0.0.255.255</mask>
<area>0</area>
</network>
<network>
<ip>100.100.0.0</ip>
<mask>0.0.255.255</mask>
<area>0</area>
</network>
</ospf>
</router>
</native>
</data>
</rpc-reply>
3. RESTCONF
RESTCONF, defined in RFC 8040, is used to programmatically interface with data defined in YANG
models while also using the datastore concepts defined in NETCONF.
There is a common misconception that RESTCONF is meant to replace NETCONF, but this is not the
case. Both are very common methods used for programmability and data manipulation. If fact,
RESTCONF uses the same YANG models as NETCONF and Cisco IOS XE.
The goal of RESTCONF is to provide a RESTful API experience while still leveraging the device
abstraction capabilities provided by NETCONF.
The RESTCONF requests and responses can use either JSON or XML structured data formats.
RESTCONF GET
------------------------
URL: https://10.85.116.59:443/restconf/data/Cisco-IOS-XE-native:native/logging/
monitor/severity
Headers: {'Accept-Encoding': 'gzip, deflate', 'Accept': 'application/
yang-data+json, application/yang-data.errors+json'}
Body:
RESTCONF RESPONSE
----------------------------
200
{
"Cisco-IOS-XE-native:severity": "critical"
}
QUIZ#
1. True or false: Python is considered one of the most difficult programming languages
a. True
b. False
2. To authenticate with Cisco’s DNA Center, which type of HTTP request method must
be used?
a. PUT
b. PATCH
c. GET
d. POST
e. HEAD
4. When using the Cisco vManage Authentication API, what is the Headers ContentType that is used?
a. MD5
b. X-Auth-Token
c. SSH
d. x-www-form-urlencoded
e. JSON
a.
"user": "root",
"father": "Jason",
"mother": "Jamie",
"friend": "Luke"
b.
<users>
<user>
<name>root</name>
</user>
<user>
<name>Jason</name>
</user>
<user>
<name>Jamie</name>
</user>
<user>
<name>Luke</name>
</user>
</users>
c.
root
Jason
Jamie
Luke
d.
[users[root|Jason|Jamie|Luke]]
a. 201
b. 400
c. 401
d. 403
e. 404
7. In Python, why would you use three quotation marks in a row? (Choose two.)
b. To start a function
c. To represent a logical OR
a.
dnac = {
"host": "sandboxdnac.cisco.com",
"port": 443,
"username": "devnetuser",
"password": "Cisco123!"
b.
[users[root|Jason|Jamie|Luke]]
c.
url = "https://{}/api/system/v1/auth/token".
format(host)
auth=HTTPBasicAuth(username, password),
headers=headers, verify=False)
return response.json()["Token"]
d.
print(dnac_devices)
a.
dnac = {
"host": "sandboxdnac.cisco.com",
"port": 443,
"username": "devnetuser",
"password": "Cisco123!"
b.
[users[root|Jason|Jamie|Luke]]
c.
url = "https://{}/api/system/v1/auth/token".
format(host)
auth=HTTPBasicAuth(username, password),
headers=headers, verify=False)
return response.json()["Token"]
d.
print(dnac_devices)
10. When using the Cisco DNA Center Token API, what authentication method is used?
a. MD5
b. X-Auth-Token
c. SSH
d. Basic authentication
e. JSON
11. What is the DevNet Community page used for? (Choose two.)
a. To ask questions
b. To exchange code
12. When using GitHub, what is the purpose of a repository? (Choose three.)
13. Why is using the command-line interface (CLI) to configure a large number of devices
b. The CLI is quick and efficient for configuring many devices simultaneously.
14. Which of the following are part of the YANG model? (Choose two.)
a. Type
b. Leaf
c. Container
d. String
e. Method
ANSWERS:
1B
2D
3B
4D
5A
6C
7 A, D
8A
9 C, D
10 D
11 A, D
12 A, C, D
13 A, D
14 B, C
EEM can take action when one of these messages show up.
ROUTER(config)#
The applet is called “INTERFACE_DOWN” and the event is a syslog pattern that matches the text
when an interface goes down. When this occurs, we run a number of commands. What happens is
that whenever someone shuts the interface, EEM will do a “no shut” on it.
This will show the commands that EEM runs when the event occurs. Let’s do a shut on that
interface:
ROUTER (config-if)#shutdown
ROUTER #
The interface went down, EEM runs the commands and the interface is up again. Simple but I think
this is a good example to demonstrate how EEM works.
ROUTER (config)#
The event that I used is a syslog message that should look familiar. The first two actions are executed
on the CLI but the third action is for the e-mail. It will send a message to
[email protected] through SMTP-server “smtp.networkjourney.com”.
Let’s give it a try. I have to enable another debug if I want to see the mail action:
Once the OSPF neighbor adjacency is established, I’ll shut the interface on one of the routers so it
breaks:
R1(config-if)#shutdown
ROUTER #
OSPF: Build router LSA for area 0, router ID 192.168.12.2, seq 0x8000000B, process 1
My router isn’t connected to the Internet but you can see it’s trying to contact the SMTP server and
send an e-mail. It also enabled the OSPF adjacency debug thanks to the CLI commands.
2. CLI Events
The previous two examples used syslog messages as the event but you can also take action based on
commands that are used on the CLI.
ROUTER (config)#
As you can see above the event is a CLI pattern. the “sync yes” parameter is required, this tells EEM
to run the script before running the “show run” command. When the script is done, it sets the exit
status to 0. Basically this means that whenever someone uses the “show run” command, the script
will run “show run | exclude interface” instead and gives you the output.
Building configuration...
You will see the output of the running configuration and if you left the debug on, you’ll see what
EEM is doing behind the scenes:
ROUTER #
Somewhere further down the running-config you can see that the lines with “interface” in them
were removed:
duplex auto
speed auto
3. Interface Events
You have seen syslog and CLI pattern events, but we have some others. What about interface
counters? It might be useful to perform an action when some interface counters have a certain
value. Here’s an example:
Let’s create a script that does something when the interface load hits a certain value. To make this
work, it’s best to change the load interval of the interface first:
ROUTER (config-if)#load-interval 30
By using this command, the router will calculate the load of the interface every 30 seconds, the
default is 5 minutes. Let’s create the script:
ROUTER (config)#
event interface name FastEthernet0/0 parameter rxload entry-op gt entry-val 10 entry-type value
poll-interval 10
This event is a bit harder to read…when the rx load of the interface is above 10/255 then we will
take action. Every 10 seconds we will check if we reached this value or not. When the event occurs, a
syslog message is produced.
Once the interface rx load is above 10 you’ll see the following message on the console:
ROUTER #
4. Scheduling Events
Instead of launching actions based on syslog or CLI messages we can also use scheduled tasks. This
means that you can run actions every X minutes / hours / days etc. Here’s an example:
ROUTER (config)#
action 3.0 syslog priority informational msg "Configuration has been saved"
This script runs every 60 seconds and runs the “write memory” command. Once it’s done, it will
produce a syslog message. After waiting for 60 seconds we’ll see this:
ROUTER #
ROUTER (config-applet)#event ?
nf NF Event
Some other useful events are changes in the routing table, IP SLA, object tracking and configuration
changes. There is also a big list of possible actions:
add Add
divide Divide
if if conditional
multiply Multiply
subtract Subtract
Running CLI commands and sending e-mails are maybe the most important ones but you can also
generate SNMP traps or reload the router.
ip sla 1
icmp-echo 192.168.12.2
frequency 10
As soon as the object goes down, EEM will perform two actions:
We’ll also configure an action that will be performed when the object is up again:
Once the object is up, we will generate a syslog message. Let’s verify our work…
Verifications:
Number of successes: 56
Number of failures: 0
R2(config-if)#shutdown
ROUTER #
The first message is produced by object tracking. It notices that IP SLA has reported a failure. The
second message is produced by EEM and it’s the first action that we configured, the syslog message.
ROUTER #
PYTHON 3.X
PYTHON THEORY BASIC TO ADVANCE
PYTHON3
THEORY.pdf
TELNETLIB #1
import telnetlib
HOST = "172.16.221.106"
user = "admin"
password = "cisco"
print(tn.read_all().decode(utf8)) # Read all data until EOF; block until connection closed.
TELNETLIB #2
import getpass
import telnetlib
HOST = "172.16.221.106"
user = "admin"
password = "cisco"
print(tn.read_all().decode('utf8')) # Read all data until end of file <EOF>; block until connection
closed
NETMIKO #1
from netmiko import Netmiko
net_connect.disconnect()
NETMIKO #2
from netmiko import Netmiko
from netmiko import ConnectHandler #connecthandler = functions
NAPALM #1
from napalm import get_network_driver
#import json
driver123 = get_network_driver('ios')
ios123.close()
ANSIBLE
There are 3 main files in the Ansible directory,
1. hosts,
2. ansible.cfg, and
3. Ansible Playbook file.
ANSIBLE #1
root@ubuntu:/etc/ansible# nano hosts
[AUTOMATION-SWITCHES]
192.168.32.200 ansible_ssh_user=admin ansible_ssh_pass=cisco
#[AUTOMATION-SWITCHES:vars]
#ansible_network_os=ios
Create 1ansible.yml
---
- hosts: AUTOMATION-SWITCHES
gather_facts: false
connection: local
gather_facts: network_cli
tasks:
- name: show run
ios_command:
commands:
- show ip int br
ANSIBLE #2
---
- name: Running show commands on Cisco IOS
hosts: AUTOMATION-SWITCHES
gather_facts: false
connection: network_cli
tasks:
- name: Run multiple commands on Cisco IOS nodes
ios_command: #ansible module
commands: #commands to run
- show version
- show ip interface brief