|
| 1 | +from prettyprinter import pprint |
| 2 | +from genie.testbed import load |
| 3 | +from unicon.eal.dialogs import Dialog, Statement |
| 4 | + |
| 5 | + |
| 6 | +# Function to handle the prompt |
| 7 | +def handle_destination_prompt(spawn, session, context): |
| 8 | + spawn.sendline('') # Sending an empty line as response to accept the default |
| 9 | + |
| 10 | + |
| 11 | +class PYATSConnection: |
| 12 | + def __init__(self): |
| 13 | + self.__testbed = load("./res/testbeds/testbed.yaml") |
| 14 | + |
| 15 | + def get_device_by_role(self, role): |
| 16 | + """ |
| 17 | + Retrieves a list of devices that match a specific role from the testbed. |
| 18 | + This function filters devices based on their assigned role attribute, useful for targeting specific types of devices in network scripts. |
| 19 | + """ |
| 20 | + return [device for device in self.__testbed.devices.values() if device.role == role] |
| 21 | + |
| 22 | + def __find_device_by_ip(self, ip): |
| 23 | + """ |
| 24 | + Searches for and returns a device object based on its IP address. |
| 25 | + This function iterates through all devices in the testbed, checking each one's SSH connection IP address against the provided IP. |
| 26 | + """ |
| 27 | + for device_name, device in self.__testbed.devices.items(): |
| 28 | + if ip == str(device.connections['ssh']['ip']): |
| 29 | + return device |
| 30 | + |
| 31 | + return None |
| 32 | + |
| 33 | + def get_device_running_config(self, device): |
| 34 | + """ |
| 35 | + Connects to a specified device and retrieves its running configuration using the learn('config') method from PyATS, |
| 36 | + which abstracts and structures the device's configuration. |
| 37 | + """ |
| 38 | + if device is not None: |
| 39 | + pprint(type(device)) |
| 40 | + device.connect(init_config_commands=[]) |
| 41 | + return device.learn('config') |
| 42 | + else: |
| 43 | + return None |
| 44 | + |
| 45 | + def search_and_replace_device_running_config(self, device, search="ip tacacs source-interface Vlan1"): |
| 46 | + """ |
| 47 | + Searches for a specific configuration line within a device's running configuration and replaces it if found. |
| 48 | + It demonstrates modifying device configurations programmatically, such as changing TACACS source interface settings. |
| 49 | + """ |
| 50 | + if device is not None: |
| 51 | + device.connect(init_config_commands=[]) |
| 52 | + output = device.execute(f'show run | include {search}') |
| 53 | + print(f"output of {search}: {output}") |
| 54 | + if search in output: |
| 55 | + # Unconfigure the old source interface and configure the new one |
| 56 | + device.configure('no ip tacacs source-interface Vlan1') |
| 57 | + device.configure('ip tacacs source-interface Vlan128') |
| 58 | + else: |
| 59 | + return None |
| 60 | + |
| 61 | + def search_device_trunk_interfaces(self, device): |
| 62 | + """ |
| 63 | + Examines a device for trunk interfaces and adjusts VLAN settings on those trunks. |
| 64 | + It also provides an example of how to parse and modify interface configurations based on operational and administrative criteria. |
| 65 | + """ |
| 66 | + if device is not None: |
| 67 | + device.connect(init_config_commands=[]) |
| 68 | + interfaces = device.parse('show interfaces switchport') |
| 69 | + for interface_name, interface_data in interfaces.items(): |
| 70 | + operational_mode = interface_data.get("operational_mode", "") |
| 71 | + administrative_mode = interface_data.get("switchport_mode", "") |
| 72 | + if operational_mode == "trunk" and administrative_mode == "trunk": |
| 73 | + vlan_list = [] |
| 74 | + trunk_vlans = interface_data.get('trunk_vlans', '') |
| 75 | + # Handle VLAN ranges like "800-900" |
| 76 | + for vlan_range in trunk_vlans.split(','): |
| 77 | + if '-' in vlan_range: |
| 78 | + start_vlan, end_vlan = vlan_range.split('-') |
| 79 | + vlan_list.extend(range(int(start_vlan), int(end_vlan) + 1)) |
| 80 | + else: |
| 81 | + if vlan_range: |
| 82 | + if vlan_range != "all": |
| 83 | + vlan_list.append(int(vlan_range)) |
| 84 | + |
| 85 | + config_commands = [f"interface {interface_name}"] |
| 86 | + |
| 87 | + # Check if VLAN 128 is in the list |
| 88 | + print(f"{interface_name} VLAN LIST: {vlan_list}") |
| 89 | + |
| 90 | + if 128 not in vlan_list: |
| 91 | + config_commands += [ |
| 92 | + "switchport trunk allowed vlan add 128" |
| 93 | + ] |
| 94 | + if 1 in vlan_list: |
| 95 | + config_commands += [ |
| 96 | + "switchport trunk allowed vlan remove 1" |
| 97 | + ] |
| 98 | + if len(config_commands) > 1: |
| 99 | + print(config_commands) |
| 100 | + device.configure(config_commands) |
| 101 | + else: |
| 102 | + return None |
| 103 | + |
| 104 | + def change_trunking_encapsulation_vlan(self, device, current_vlan: int, updated_vlan: int): |
| 105 | + """ |
| 106 | + Examines a device for trunk interfaces and adjusts VLAN settings on those trunks. |
| 107 | + It also provides an example of how to parse and modify interface configurations based on operational and administrative criteria. |
| 108 | + """ |
| 109 | + if device is not None: |
| 110 | + device.connect(init_config_commands=[]) |
| 111 | + interfaces = device.parse('show ip interface brief') |
| 112 | + for interface_name, interface_data in interfaces["interface"].items(): |
| 113 | + print(interface_name) |
| 114 | + if "." in interface_name: |
| 115 | + interface_details = device.parse(f'show interface {interface_name}') |
| 116 | + if interface_details[interface_name]['encapsulations']['encapsulation'] == "dot1q" and int( |
| 117 | + interface_details[interface_name]['encapsulations']['first_dot1q']) == current_vlan: |
| 118 | + config_commands = [f"interface {interface_name}", f"encapsulation dot1Q {updated_vlan} native"] |
| 119 | + device.configure(config_commands) |
| 120 | + |
| 121 | + def update_device_access_vlans_on_interfaces(self, device, current_access_vlan: int, updated_access_vlan: int): |
| 122 | + """ |
| 123 | + Updates the access VLANs on all interfaces of a device that are set to a specific VLAN. |
| 124 | + This function can be crucial in network migrations or reconfigurations where VLAN changes are common. |
| 125 | + """ |
| 126 | + if device is not None: |
| 127 | + device.connect(init_config_commands=[]) |
| 128 | + interfaces = device.parse('show interfaces switchport') |
| 129 | + for interface_name, interface_data in interfaces.items(): |
| 130 | + operational_mode = interface_data.get("operational_mode", "") |
| 131 | + administrative_mode = interface_data.get("switchport_mode", "") |
| 132 | + print(interface_data) |
| 133 | + input() |
| 134 | + if operational_mode == "static access" or operational_mode == "down": # ACCESS, DOWN, TRUNK |
| 135 | + if administrative_mode == "static access": # TRUNK OR ACCESS |
| 136 | + access_vlan = interface_data['access_vlan'] |
| 137 | + if current_access_vlan == int(access_vlan): |
| 138 | + config_commands = [f'interface {interface_name}', |
| 139 | + f"switchport access vlan {updated_access_vlan}", |
| 140 | + f"authentication event server dead action reinitialize vlan {updated_access_vlan}"] |
| 141 | + device.configure(config_commands) |
| 142 | + |
| 143 | + def save_current_config(self, device, date): |
| 144 | + """ |
| 145 | + Saves the current configuration of the device to its local storage. |
| 146 | + This function includes handling for prompts that may appear during the save process, |
| 147 | + making it robust for automated scripts. |
| 148 | + """ |
| 149 | + if device is not None: |
| 150 | + # Create the dialog |
| 151 | + dialog = Dialog([ |
| 152 | + Statement(pattern=r'Destination filename \[(.*)\]\?', |
| 153 | + action=handle_destination_prompt, |
| 154 | + loop_continue=True, |
| 155 | + continue_timer=False) |
| 156 | + ]) |
| 157 | + |
| 158 | + device.connect(init_config_commands=[]) |
| 159 | + device.execute(f"copy run flash:sh-run-{date}.txt", reply=dialog) |
| 160 | + |
| 161 | + |
| 162 | + def update_svi(self, device, svi_interface, updated_svi_interface): |
| 163 | + """ |
| 164 | + Copies the configuration from one switched virtual interface (SVI) to another and shuts down the original SVI. |
| 165 | + This function demonstrates advanced manipulation of interface configurations, |
| 166 | + useful for significant network restructurings or consolidations. |
| 167 | + """ |
| 168 | + if device is not None: |
| 169 | + device.connect(init_config_commands=[]) |
| 170 | + # Execute command to get the configuration for the specified SVI interface |
| 171 | + output = device.execute(f'show run interface {svi_interface}') |
| 172 | + |
| 173 | + # Initialize a list to hold the configuration commands |
| 174 | + config_commands = [] |
| 175 | + capturing = False |
| 176 | + |
| 177 | + # Process each line in the output to capture the relevant configuration |
| 178 | + for line in output.splitlines(): |
| 179 | + # Check if the current line is the start of the interface configuration |
| 180 | + if line.strip().startswith(f"interface {svi_interface}"): |
| 181 | + capturing = True |
| 182 | + continue # Skip adding the interface declaration line itself |
| 183 | + |
| 184 | + # Check if we are currently capturing and if the line is not a sub-interface or another main interface |
| 185 | + if capturing and line.startswith(' interface'): |
| 186 | + break # Stop capturing on encountering a new interface definition |
| 187 | + |
| 188 | + # If capturing, add the line to our commands list |
| 189 | + if capturing: |
| 190 | + config_commands.append(line.strip()) |
| 191 | + |
| 192 | + #Default the old interface |
| 193 | + shutdown_interface_commands = [f"default interface {svi_interface}",f"interface {svi_interface}", f"shut"] |
| 194 | + device.configure(shutdown_interface_commands) |
| 195 | + # Prepare the new interface configuration commands |
| 196 | + new_interface_commands = [f"interface {updated_svi_interface}"] + config_commands |
| 197 | + |
| 198 | + # Apply configuration to the new interface |
| 199 | + try: |
| 200 | + device.configure(new_interface_commands) |
| 201 | + print(f"Configuration successfully applied to {updated_svi_interface}") |
| 202 | + except Exception as e: |
| 203 | + print(f"Error during configuration transfer: {str(e)}") |
| 204 | + |
| 205 | + |
| 206 | + |
0 commit comments