Skip to content

Commit

Permalink
Adding a new example for Netmiko and Loopback Manipulation (#10)
Browse files Browse the repository at this point in the history
* added device_info file for examples

* Demo editing on GitHub for git pull example.

* New file to retrieve Loopback Interface Details

* added try block for better error handling

* added create loopback script

* delete loopback script

* requirements file

* added readme

* Updated to add the netmiko example
  • Loading branch information
hpreston authored Mar 22, 2019
1 parent 7f259e0 commit ba89835
Show file tree
Hide file tree
Showing 7 changed files with 348 additions and 18 deletions.
37 changes: 19 additions & 18 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,37 +1,38 @@
# Network Automation with Python Code Samples
# Network Automation with Python Code Samples

A collection of Python Code Samples for Network Management. Includes samples that leverage on-box libraries, as well as samples that use exposed external APIs (NETCONF/RESTCONF, SNMP, SSH, REST, etc). Some examples make use of available SDKs.

## On-Box Examples
## On-Box Examples

Many Cisco switches and routers provide an on-box Python Interpreter that can be leveraged to execute scripts and programs directly on end devices. In addition to the interpreter, Python libraries are included that provide direct access to the underlying devices operations to execute CLI commands, or monitor for events.

### Sample Code
### Sample Code

| Code Sample | Description |
| --- | --- |
| [Execute CLI via Python](/Py-sho-ver-onbox) | This example is about as simple as it gets. By leveraging the CLI library, we execute the “show version” command on the box. |
| [TDR Test Every Interface](/tdr-test) | This example once again leverages the CLI library, but to do something a bit more interesting. A TDR test is run on every interface in “up” status. |
| [EEM Config Changes to Spark](/eem_configdiff_to_spark) | In this example, the EEM library is used to monitor for configuration changes. When one occurs a message is sent to a Cisco Spark Room. |
| Code Sample | Description |
| --- | --- |
| [Execute CLI via Python](/Py-sho-ver-onbox) | This example is about as simple as it gets. By leveraging the CLI library, we execute the “show version” command on the box. |
| [TDR Test Every Interface](/tdr-test) | This example once again leverages the CLI library, but to do something a bit more interesting. A TDR test is run on every interface in “up” status. |
| [EEM Config Changes to Spark](/eem_configdiff_to_spark) | In this example, the EEM library is used to monitor for configuration changes. When one occurs a message is sent to a Cisco Spark Room. |
| [Python with Eventing Example](/EEM-interface-move-routes) | Use the EEM and Python together to script based on local events. |
| [EEM + Python + Spark ChatOps](/spark_checkin) | Use the EEM to monitor for config changes and send a Spark Message |
| [EEM + Python + Email alert](/PortFlap_email_alert) | This example leverages the CLI library and using the EEM feature to monitor for interface flapping and send an email alert |


## Off-Box Examples
## Off-Box Examples

Here are few Python scripts that can interact with network elements using one of the many exposed interfaces (NETCONF, RESTCONF, SNMP, SSH, etc). Many of these scripts could also be run on-box, however they don’t leverage any of the unique libraries available on device.

| Code Sample | Description |
| --- | --- |
| [MIB Walk with Python](/snmp_entity) | In this example, we perform a MIB walk against a device leveraging the “netsnmp” library for Python. |
| [NETCONF Connection with Python](/netconf_entity) | This example shows the basics of connecting to a device with NETCONF using the “ncclient” library for Python. |
| [Configure Interface IP Address with RESTCONF](/restconf_update_ipaddress) | In this example the newly ratified RESTCONF standard is used to configure the IP Address on an interface. |
| Code Sample | Description |
| --- | --- |
| [Netmiko and CLI Example for Interface Management](/netmiko-interface-example) | These are a series of python scripts for retrieving, creating, deleting a Loopback Interface with Python. |
| [MIB Walk with Python](/snmp_entity) | In this example, we perform a MIB walk against a device leveraging the “netsnmp” library for Python. |
| [NETCONF Connection with Python](/netconf_entity) | This example shows the basics of connecting to a device with NETCONF using the “ncclient” library for Python. |
| [Configure Interface IP Address with RESTCONF](/restconf_update_ipaddress) | In this example the newly ratified RESTCONF standard is used to configure the IP Address on an interface. |
| [Get Inventory from APIC-EM](/apic-em_get_inventory_stats) | APIC-EM maintains an inventory database of the entire network. In this example Python is used to retrieve that information using the REST API. |
| [Get Host List from APIC-EM](/apic-em_get_hosts) | APIC-EM maintains a list of all clients connected to the network devices discovered by APIC-EM. This example queries the APIC-EM for the list, and display’s it in a simple table. |
| [Get Host List from APIC-EM](/apic-em_get_hosts) | APIC-EM maintains a list of all clients connected to the network devices discovered by APIC-EM. This example queries the APIC-EM for the list, and display’s it in a simple table. |
| [Retrieve Tenants from ACI APIC](/acitoolkit_show_tenants) | This example leverages the ACI Toolkit to connect to an APIC controller and retrieve the list of Tenants configured. |
| [Basic NETCONF Get](/NC-get-config) | A basic ncclient example to `<get>` NETCONF Data |
| [Basic NETCONF Get](/NC-get-config) | A basic ncclient example to `<get>` NETCONF Data |
| [Basic NETCONF Edit](/NC-edit-config) | A basic ncclient example to `<edit-config>` NETCONF Data |
| [NETCONF XPATH Example](/NC-get-config-xpath) | Use the XPATH feature when making a NETCONF Requests |
| [Model Based AAA](/model-based-aaa) | These example scripts are for Model Based AAA to get, edit and delete the rule-lists for privilege level users and Groups by using ietf-netconf-acm.yang data model |
| [RESTCONF](/RESTCONF) | These example scripts are for RESTCONF to retrieve and configure the switch using different operations such as Get, Delete, Put, Post and Patch. |
| [Model Based AAA](/model-based-aaa) | These example scripts are for Model Based AAA to get, edit and delete the rule-lists for privilege level users and Groups by using ietf-netconf-acm.yang data model |
| [RESTCONF](/RESTCONF) | These example scripts are for RESTCONF to retrieve and configure the switch using different operations such as Get, Delete, Put, Post and Patch. |
96 changes: 96 additions & 0 deletions netmiko-interface-example/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
# Using Netmiko to work with Interfaces

These example scripts use the Netmiko Python library to interact with a device through CLI

These Python scripts leverages Netmiko to:
- Create Loopback 103
- Retrieve details about Loopback 103
- Delete Loopback 103

This script has been tested with Python 3.6, however may work with other versions.

## DevNet Sandbox

This script targets the [IOS XE DevNet Always On Sandbox](https://devnetsandbox.cisco.com/RM/Diagram/Index/27d9747a-db48-4565-8d44-df318fce37ad?diagramType=Topology) that leverages a CSR1000v as a target.

To execute this script against a different device, create a new device dictionary in `device_info.py` for your device. Then import this new dictionary instead of `ios_xe1` in the scripts.

## Requirements

Python

- netmiko

# Getting Started

* Clone the Python Examples and change into the directory.

```bash
git clone //github.com/CiscoDevNet/python_code_samples_network
cd netmiko-interface-example
```

* Create and activate a virtualenv

```bash
virtualenv venv --python=python3
source venv/bin/activate
```

* Install the requirements

```bash
pip install -r requirements.text
```

* Run the scripts

```
# Run the get script to retrieve interface
$ python netmiko-get-interface.py

# Output - Interface not there yet... ^
% Invalid input detected at '^' marker.

There was an error, Loopback103 might not exist.

# Run the create script to create interface
$ python netmiko-create-interface.py

# Output - what was configured
The following configuration was sent:
config term
Enter configuration commands, one per line. End with CNTL/Z.
csr1000v(config)#interface Loopback103
csr1000v(config-if)#description Demo interface by CLI and netmiko
csr1000v(config-if)#ip address 192.168.103.1 255.255.255.0
csr1000v(config-if)#no shut
csr1000v(config-if)#end
csr1000v#

# Run the get script again
$ python netmiko-get-interface.py

# Output - there it is!
Building configuration...

Current configuration : 116 bytes
!
interface Loopback103
description Demo interface by CLI and netmiko
ip address 192.168.103.1 255.255.255.0
end

The interface Loopback103 has ip address 192.168.103.1/255.255.255.0

# Run the delete script to remove the interface
$ python netmiko-delete-interface.py

# Output - what was sent to remove the interface
The following configuration was sent:
config term
Enter configuration commands, one per line. End with CNTL/Z.
csr1000v(config)#no interface Loopback103
csr1000v(config)#end
csr1000v#
```
56 changes: 56 additions & 0 deletions netmiko-interface-example/device_info.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
#! /usr/bin/env python
"""Device Details for DevNet Sandboxes
This script is imported into other code.
Copyright (c) 2018 Cisco and/or its affiliates.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

__author__ = "Hank Preston"
__author_email__ = "hapresto@cisco.com"
__copyright__ = "Copyright (c) 2016 Cisco Systems, Inc."
__license__ = "MIT"

# DevNet Always-On NETCONF/YANG & RESTCONF Sandbox Device
# https://devnetsandbox.cisco.com/RM/Diagram/Index/27d9747a-db48-4565-8d44-df318fce37ad?diagramType=Topology
ios_xe1 = {
"address": "ios-xe-mgmt.cisco.com",
"netconf_port": 10000,
"restconf_port": 9443,
"ssh_port": 8181,
"username": "root",
"password": "D_Vay!_10&",
"device_type": "cisco_ios"
}

# DevNet Always-On Sandbox NX-OS
#
nxos1 = {
"address": "sbx-nxos-mgmt.cisco.com",
"netconf_port": 10000,
"restconf_port": 443,
"ssh_port": 818122,
"username": "admin",
"password": "Admin_1234!",
"device_type": "cisco_nxos"
}

# Sample GitHub Editor Comment.
58 changes: 58 additions & 0 deletions netmiko-interface-example/netmiko-create-interface.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
#! /usr/bin/env python
"""Sample use of the netmiko library for CLI interfacing
This script will create new configuration on a device.
Copyright (c) 2018 Cisco and/or its affiliates.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

# Import libraries
from netmiko import ConnectHandler

from device_info import ios_xe1 as device # noqa

# New Loopback Details
loopback = {"int_name": "Loopback103",
"description": "Demo interface by CLI and netmiko",
"ip": "192.168.103.1",
"netmask": "255.255.255.0"}

# Create a CLI configuration
interface_config = [
"interface {}".format(loopback["int_name"]),
"description {}".format(loopback["description"]),
"ip address {} {}".format(loopback["ip"], loopback["netmask"]),
"no shut"
]

# Open CLI connection to device
with ConnectHandler(ip = device["address"],
port = device["ssh_port"],
username = device["username"],
password = device["password"],
device_type = device["device_type"]) as ch:

# Send configuration to device
output = ch.send_config_set(interface_config)

# Print the raw command output to the screen
print("The following configuration was sent: ")
print(output)
52 changes: 52 additions & 0 deletions netmiko-interface-example/netmiko-delete-interface.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
#! /usr/bin/env python
"""Sample use of the netmiko library for CLI interfacing
This script will delete configuration on a device.
Copyright (c) 2018 Cisco and/or its affiliates.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

# Import libraries
from netmiko import ConnectHandler

from device_info import ios_xe1 as device # noqa

# New Loopback Details
loopback = {"int_name": "Loopback103"}

# Create a CLI configuration
interface_config = [
"no interface {}".format(loopback["int_name"])
]

# Open CLI connection to device
with ConnectHandler(ip = device["address"],
port = device["ssh_port"],
username = device["username"],
password = device["password"],
device_type = device["device_type"]) as ch:

# Send configuration to device
output = ch.send_config_set(interface_config)

# Print the raw command output to the screen
print("The following configuration was sent: ")
print(output)
66 changes: 66 additions & 0 deletions netmiko-interface-example/netmiko-get-interface.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
#! /usr/bin/env python
"""Sample use of the netmiko library for CLI interfacing
This script will retrieve information from a device.
Copyright (c) 2018 Cisco and/or its affiliates.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

# Import libraries
from netmiko import ConnectHandler
import re

from device_info import ios_xe1 as device # noqa

# Create a CLI command template
show_interface_config_temp = "show running-config interface {}"

# Open CLI connection to device
with ConnectHandler(ip = device["address"],
port = device["ssh_port"],
username = device["username"],
password = device["password"],
device_type = device["device_type"]) as ch:

# Create desired CLI command and send to device
command = show_interface_config_temp.format("Loopback103")
interface = ch.send_command(command)

# Print the raw command output to the screen
print(interface)

try:
# Use regular expressions to parse the output for desired data
name = re.search(r'interface (.*)', interface).group(1)
description = re.search(r'description (.*)', interface).group(1)
ip_info = re.search(r'ip address (.*) (.*)', interface)
ip = ip_info.group(1)
netmask = ip_info.group(2)

# Print the info to the screen
print("The interface {name} has ip address {ip}/{mask}".format(
name = name,
ip = ip,
mask = netmask,
)
)
except Exception:
print("There was an error, Loopback103 might not exist.")
1 change: 1 addition & 0 deletions netmiko-interface-example/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
netmiko

0 comments on commit ba89835

Please sign in to comment.