Network Automation NAPALM (Python networking scripts examples)
In this network automation example, we will be using context manager to connect devices. The context manager is very useful if the number of devices is greater than 100. All the opening and closing of the session will be handled automatically. We don’t have to use the open() and close() methods, and this will save us time while writing the code.
We will create a list with two IP addresses. The first IP address is a valid one, while the second one is invalid. We will print ‘Connection Successful’ for a valid IP address and ‘Connection Failed’ for an invalid IP address.
The first step is to Import get_network_driver from napalm
from napalm import get_network_driver
In the next step, we will create a list with two IP addresses. Each IP address in a list is called an element or item. The creation of the list is done on the second line.
ip_address = ['1.1.1.1','131.226.217.143']
Since we are trying to connect a Cisco IOS router, the network driver will be “ios”. This is a very crucial step because if we supplied the wrong driver, the connection would fail.
driver = get_network_driver('ios')
Now, it is time to use a for loop to attempt to connect to all the IP addresses in a list.
for ip in ip_address:
try:
with driver(ip,'developer','C1sco12345') as device:
print('Connection Successful to %s' %ip)
except:
print('Connection failed to %s' %ip)
Here, we are not using the open() and close() methods. The opening and closing of the session will be managed automatically by the context manager.
We get the output message “Connection Successful” when the connection is open, otherwise “Connection failed.”
Output
Connection failed to 1.1.1.1
Connection Successful to 131.226.217.143
Process finished with exit code 0
Complete Code
from napalm import get_network_driver
ip_address = ['1.1.1.1','131.226.217.143']
driver = get_network_driver('ios')
for ip in ip_address:
try:
with driver(ip,'developer','C1sco12345') as device:
print('Connection Successful to %s' %ip)
except:
print('Connection failed to %s' %ip)