Skip to content

Commit ba89835

Browse files
authored
Adding a new example for Netmiko and Loopback Manipulation (CiscoDevNet#10)
* 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
1 parent 7f259e0 commit ba89835

7 files changed

+348
-18
lines changed

README.md

Lines changed: 19 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,38 @@
1-
# Network Automation with Python Code Samples
1+
# Network Automation with Python Code Samples
22

33
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.
44

5-
## On-Box Examples
5+
## On-Box Examples
66

77
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.
88

9-
### Sample Code
9+
### Sample Code
1010

11-
| Code Sample | Description |
12-
| --- | --- |
13-
| [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. |
14-
| [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. |
15-
| [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. |
11+
| Code Sample | Description |
12+
| --- | --- |
13+
| [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. |
14+
| [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. |
15+
| [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. |
1616
| [Python with Eventing Example](/EEM-interface-move-routes) | Use the EEM and Python together to script based on local events. |
1717
| [EEM + Python + Spark ChatOps](/spark_checkin) | Use the EEM to monitor for config changes and send a Spark Message |
1818
| [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 |
1919

2020

21-
## Off-Box Examples
21+
## Off-Box Examples
2222

2323
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.
2424

25-
| Code Sample | Description |
26-
| --- | --- |
27-
| [MIB Walk with Python](/snmp_entity) | In this example, we perform a MIB walk against a device leveraging the “netsnmp” library for Python. |
28-
| [NETCONF Connection with Python](/netconf_entity) | This example shows the basics of connecting to a device with NETCONF using the “ncclient” library for Python. |
29-
| [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. |
25+
| Code Sample | Description |
26+
| --- | --- |
27+
| [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. |
28+
| [MIB Walk with Python](/snmp_entity) | In this example, we perform a MIB walk against a device leveraging the “netsnmp” library for Python. |
29+
| [NETCONF Connection with Python](/netconf_entity) | This example shows the basics of connecting to a device with NETCONF using the “ncclient” library for Python. |
30+
| [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. |
3031
| [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. |
31-
| [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. |
32+
| [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. |
3233
| [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. |
33-
| [Basic NETCONF Get](/NC-get-config) | A basic ncclient example to `<get>` NETCONF Data |
34+
| [Basic NETCONF Get](/NC-get-config) | A basic ncclient example to `<get>` NETCONF Data |
3435
| [Basic NETCONF Edit](/NC-edit-config) | A basic ncclient example to `<edit-config>` NETCONF Data |
3536
| [NETCONF XPATH Example](/NC-get-config-xpath) | Use the XPATH feature when making a NETCONF Requests |
36-
| [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 |
37-
| [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. |
37+
| [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 |
38+
| [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. |

netmiko-interface-example/README.md

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
# Using Netmiko to work with Interfaces
2+
3+
These example scripts use the Netmiko Python library to interact with a device through CLI
4+
5+
These Python scripts leverages Netmiko to:
6+
- Create Loopback 103
7+
- Retrieve details about Loopback 103
8+
- Delete Loopback 103
9+
10+
This script has been tested with Python 3.6, however may work with other versions.
11+
12+
## DevNet Sandbox
13+
14+
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.
15+
16+
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.
17+
18+
## Requirements
19+
20+
Python
21+
22+
- netmiko
23+
24+
# Getting Started
25+
26+
* Clone the Python Examples and change into the directory.
27+
28+
```bash
29+
git clone //github.com/CiscoDevNet/python_code_samples_network
30+
cd netmiko-interface-example
31+
```
32+
33+
* Create and activate a virtualenv
34+
35+
```bash
36+
virtualenv venv --python=python3
37+
source venv/bin/activate
38+
```
39+
40+
* Install the requirements
41+
42+
```bash
43+
pip install -r requirements.text
44+
```
45+
46+
* Run the scripts
47+
48+
```
49+
# Run the get script to retrieve interface
50+
$ python netmiko-get-interface.py
51+
52+
# Output - Interface not there yet... ^
53+
% Invalid input detected at '^' marker.
54+
55+
There was an error, Loopback103 might not exist.
56+
57+
# Run the create script to create interface
58+
$ python netmiko-create-interface.py
59+
60+
# Output - what was configured
61+
The following configuration was sent:
62+
config term
63+
Enter configuration commands, one per line. End with CNTL/Z.
64+
csr1000v(config)#interface Loopback103
65+
csr1000v(config-if)#description Demo interface by CLI and netmiko
66+
csr1000v(config-if)#ip address 192.168.103.1 255.255.255.0
67+
csr1000v(config-if)#no shut
68+
csr1000v(config-if)#end
69+
csr1000v#
70+
71+
# Run the get script again
72+
$ python netmiko-get-interface.py
73+
74+
# Output - there it is!
75+
Building configuration...
76+
77+
Current configuration : 116 bytes
78+
!
79+
interface Loopback103
80+
description Demo interface by CLI and netmiko
81+
ip address 192.168.103.1 255.255.255.0
82+
end
83+
84+
The interface Loopback103 has ip address 192.168.103.1/255.255.255.0
85+
86+
# Run the delete script to remove the interface
87+
$ python netmiko-delete-interface.py
88+
89+
# Output - what was sent to remove the interface
90+
The following configuration was sent:
91+
config term
92+
Enter configuration commands, one per line. End with CNTL/Z.
93+
csr1000v(config)#no interface Loopback103
94+
csr1000v(config)#end
95+
csr1000v#
96+
```
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
#! /usr/bin/env python
2+
"""Device Details for DevNet Sandboxes
3+
4+
This script is imported into other code.
5+
6+
Copyright (c) 2018 Cisco and/or its affiliates.
7+
8+
Permission is hereby granted, free of charge, to any person obtaining a copy
9+
of this software and associated documentation files (the "Software"), to deal
10+
in the Software without restriction, including without limitation the rights
11+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12+
copies of the Software, and to permit persons to whom the Software is
13+
furnished to do so, subject to the following conditions:
14+
15+
The above copyright notice and this permission notice shall be included in all
16+
copies or substantial portions of the Software.
17+
18+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24+
SOFTWARE.
25+
"""
26+
27+
__author__ = "Hank Preston"
28+
__author_email__ = "hapresto@cisco.com"
29+
__copyright__ = "Copyright (c) 2016 Cisco Systems, Inc."
30+
__license__ = "MIT"
31+
32+
# DevNet Always-On NETCONF/YANG & RESTCONF Sandbox Device
33+
# https://devnetsandbox.cisco.com/RM/Diagram/Index/27d9747a-db48-4565-8d44-df318fce37ad?diagramType=Topology
34+
ios_xe1 = {
35+
"address": "ios-xe-mgmt.cisco.com",
36+
"netconf_port": 10000,
37+
"restconf_port": 9443,
38+
"ssh_port": 8181,
39+
"username": "root",
40+
"password": "D_Vay!_10&",
41+
"device_type": "cisco_ios"
42+
}
43+
44+
# DevNet Always-On Sandbox NX-OS
45+
#
46+
nxos1 = {
47+
"address": "sbx-nxos-mgmt.cisco.com",
48+
"netconf_port": 10000,
49+
"restconf_port": 443,
50+
"ssh_port": 818122,
51+
"username": "admin",
52+
"password": "Admin_1234!",
53+
"device_type": "cisco_nxos"
54+
}
55+
56+
# Sample GitHub Editor Comment.
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
#! /usr/bin/env python
2+
"""Sample use of the netmiko library for CLI interfacing
3+
4+
This script will create new configuration on a device.
5+
6+
Copyright (c) 2018 Cisco and/or its affiliates.
7+
8+
Permission is hereby granted, free of charge, to any person obtaining a copy
9+
of this software and associated documentation files (the "Software"), to deal
10+
in the Software without restriction, including without limitation the rights
11+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12+
copies of the Software, and to permit persons to whom the Software is
13+
furnished to do so, subject to the following conditions:
14+
15+
The above copyright notice and this permission notice shall be included in all
16+
copies or substantial portions of the Software.
17+
18+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24+
SOFTWARE.
25+
"""
26+
27+
# Import libraries
28+
from netmiko import ConnectHandler
29+
30+
from device_info import ios_xe1 as device # noqa
31+
32+
# New Loopback Details
33+
loopback = {"int_name": "Loopback103",
34+
"description": "Demo interface by CLI and netmiko",
35+
"ip": "192.168.103.1",
36+
"netmask": "255.255.255.0"}
37+
38+
# Create a CLI configuration
39+
interface_config = [
40+
"interface {}".format(loopback["int_name"]),
41+
"description {}".format(loopback["description"]),
42+
"ip address {} {}".format(loopback["ip"], loopback["netmask"]),
43+
"no shut"
44+
]
45+
46+
# Open CLI connection to device
47+
with ConnectHandler(ip = device["address"],
48+
port = device["ssh_port"],
49+
username = device["username"],
50+
password = device["password"],
51+
device_type = device["device_type"]) as ch:
52+
53+
# Send configuration to device
54+
output = ch.send_config_set(interface_config)
55+
56+
# Print the raw command output to the screen
57+
print("The following configuration was sent: ")
58+
print(output)
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
#! /usr/bin/env python
2+
"""Sample use of the netmiko library for CLI interfacing
3+
4+
This script will delete configuration on a device.
5+
6+
Copyright (c) 2018 Cisco and/or its affiliates.
7+
8+
Permission is hereby granted, free of charge, to any person obtaining a copy
9+
of this software and associated documentation files (the "Software"), to deal
10+
in the Software without restriction, including without limitation the rights
11+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12+
copies of the Software, and to permit persons to whom the Software is
13+
furnished to do so, subject to the following conditions:
14+
15+
The above copyright notice and this permission notice shall be included in all
16+
copies or substantial portions of the Software.
17+
18+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24+
SOFTWARE.
25+
"""
26+
27+
# Import libraries
28+
from netmiko import ConnectHandler
29+
30+
from device_info import ios_xe1 as device # noqa
31+
32+
# New Loopback Details
33+
loopback = {"int_name": "Loopback103"}
34+
35+
# Create a CLI configuration
36+
interface_config = [
37+
"no interface {}".format(loopback["int_name"])
38+
]
39+
40+
# Open CLI connection to device
41+
with ConnectHandler(ip = device["address"],
42+
port = device["ssh_port"],
43+
username = device["username"],
44+
password = device["password"],
45+
device_type = device["device_type"]) as ch:
46+
47+
# Send configuration to device
48+
output = ch.send_config_set(interface_config)
49+
50+
# Print the raw command output to the screen
51+
print("The following configuration was sent: ")
52+
print(output)
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
#! /usr/bin/env python
2+
"""Sample use of the netmiko library for CLI interfacing
3+
4+
This script will retrieve information from a device.
5+
6+
Copyright (c) 2018 Cisco and/or its affiliates.
7+
8+
Permission is hereby granted, free of charge, to any person obtaining a copy
9+
of this software and associated documentation files (the "Software"), to deal
10+
in the Software without restriction, including without limitation the rights
11+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12+
copies of the Software, and to permit persons to whom the Software is
13+
furnished to do so, subject to the following conditions:
14+
15+
The above copyright notice and this permission notice shall be included in all
16+
copies or substantial portions of the Software.
17+
18+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24+
SOFTWARE.
25+
"""
26+
27+
# Import libraries
28+
from netmiko import ConnectHandler
29+
import re
30+
31+
from device_info import ios_xe1 as device # noqa
32+
33+
# Create a CLI command template
34+
show_interface_config_temp = "show running-config interface {}"
35+
36+
# Open CLI connection to device
37+
with ConnectHandler(ip = device["address"],
38+
port = device["ssh_port"],
39+
username = device["username"],
40+
password = device["password"],
41+
device_type = device["device_type"]) as ch:
42+
43+
# Create desired CLI command and send to device
44+
command = show_interface_config_temp.format("Loopback103")
45+
interface = ch.send_command(command)
46+
47+
# Print the raw command output to the screen
48+
print(interface)
49+
50+
try:
51+
# Use regular expressions to parse the output for desired data
52+
name = re.search(r'interface (.*)', interface).group(1)
53+
description = re.search(r'description (.*)', interface).group(1)
54+
ip_info = re.search(r'ip address (.*) (.*)', interface)
55+
ip = ip_info.group(1)
56+
netmask = ip_info.group(2)
57+
58+
# Print the info to the screen
59+
print("The interface {name} has ip address {ip}/{mask}".format(
60+
name = name,
61+
ip = ip,
62+
mask = netmask,
63+
)
64+
)
65+
except Exception:
66+
print("There was an error, Loopback103 might not exist.")
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
netmiko

0 commit comments

Comments
 (0)