Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
2024-lonisummit-workshop-automation/lab-2/4_netmiko_seek_helper_addrs.py
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
54 lines (44 sloc)
1.87 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# pip install --user netmiko | |
from netmiko import Netmiko | |
from ciscoconfparse import CiscoConfParse | |
username = "clab" | |
password = "clab@123" | |
device_type = "cisco_xr" | |
hosts = ["172.16.x.2", "172.16.x.3", "172.16.x.4"] # TODO | |
target_ip_helper = "fill me in!" | |
for host in hosts: | |
# Create a variable that represents an SSH connection to our router. | |
connection = Netmiko( | |
username=username, password=password, device_type=device_type, ip=host | |
) | |
# Get the output for "show run". This will be raw and unformatted. | |
raw_config = connection.send_command("show run") | |
# Turn this giant singular string of output into a list of lines. | |
parser = CiscoConfParse(raw_config.split("\n")) | |
for intf in parser.find_objects("^interface .*"): | |
# Get the interface name. | |
intf_name = intf.text | |
# Give us nice messages | |
print(f"Inspecting {intf_name} on {host}...") | |
# Retrieve the helper address, if it exists. | |
helper_address_line = intf.re_search_children("^ ipv4 helper-address") | |
if not helper_address_line: | |
# Nothing to see here! Skip. | |
# Don't configure a new IP helper on interfaces that don't have one. | |
continue | |
# Get the last "word" in the line, which is the helper IP address. | |
ip = helper_address_line[-1] | |
if ip != target_ip_helper: | |
print(f"Found old IP helper!:\n{intf}") | |
commands = [ | |
intf_name, | |
f"no ipv4 helper-address {ip}", | |
f"ipv4 helper-address {target_ip_helper}", | |
"commit" | |
] | |
# Let's observe: | |
print(f"Running: {commands}") | |
connection.send_config_set(commands) | |
new_interface_config = connection.send_command(f"show run int {intf_name}") | |
print(f"Post-configuration:\n{new_interface_config}") | |
print("Done!") |