Network Automation NAPALM (Python networking scripts examples)
In some of the previous blogs of network automation example, we have used the open() and close() methods to connect and close the session with a network device. Now we will use the context manager to connect to a Cisco router in this example.
If there are some simple tasks involved, such as connecting to two or three routers and pulling their configurations, using open and close methods will be good options. However, it will not be feasible to use these methods to connect more than 100 routers in a network. The simple way is to use a context manager to handle the opening and closing of the session.
We’ll connect to a device with context manager and pull some data with commands like get_facts() and get_interfaces_ip().
First Import get_network_driver from napalm
from napalm import get_network_driver
import json
Using the appropriate driver to connect the Cisco router Here, we are trying to connect to a Cisco IOS router by using the network driver ‘ios’.
driver = get_network_driver('ios')
Use the context manager to connect to a device and close the session automatically. Below, we have used two methods get_interface_ip and get_factsÂ
with driver('131.226.217.143','developer','C1sco12345') as device:
print('Get_facts() method details')
print(json.dumps(device.get_facts(),indent=2))
print()
print('Interface Details')
print(json.dumps(device.get_interfaces_ip(), indent=2))
One thing we can notice here is that we haven’t used the “open and close” method. All opening and closing connections to a device will be handled automatically with the help of the context manager.
Output
Get_facts() method details
{
"uptime": 23760.0,
"vendor": "Cisco",
"os_version": "Virtual XE Software (X86_64_LINUX_IOSD-UNIVERSALK9-M), Version 17.3.1a, RELEASE SOFTWARE (fc3)",
"serial_number": "9ESGOBARV9D",
"model": "CSR1000V",
"hostname": "csr1000v-1",
"fqdn": "csr1000v-1.lab.devnetsandbox.local",
"interface_list": [
"GigabitEthernet1",
"GigabitEthernet2",
"GigabitEthernet3",
"Loopback56",
"Loopback100"
]
}
Interface Details
{
"GigabitEthernet1": {
"ipv4": {
"10.10.20.48": {
"prefix_length": 24
}
}
},
"GigabitEthernet2": {
"ipv4": {
"11.11.11.1": {
"prefix_length": 30
}
}
},
"Loopback56": {
"ipv4": {
"56.56.56.56": {
"prefix_length": 32
}
}
},
"Loopback100": {
"ipv4": {
"192.168.1.1": {
"prefix_length": 25
}
}
}
}
Process finished with exit code 0
Complete Code
from napalm import get_network_driver
import json
driver = get_network_driver('ios')
with driver('131.226.217.143','developer','C1sco12345') as device:
print('Get_facts() method details')
print(json.dumps(device.get_facts(),indent=2))
print()
print('Interface Details')
print(json.dumps(device.get_interfaces_ip(), indent=2))