Search code examples
pythoncisco-ios

Exception Handling in Python Script


I have the following python script that adds configurations to different Cisco IOS devices. The script works great as long as all the devices in the file allow the SSH connection and take the configs. However, if any device in the file rejects the SSH connection, the script stops dead in its tracks and doesn't move any further. How can I tweak the code to tell the script to move on if it encounters an issue logging into any of the devices? Thanks so much for any feedback.

from netmiko import ConnectHandler
import yaml
import json

with open("devices.yml") as f:
    all_devices = yaml.save_load(f)

with open("snmp_configs.txt") as g:
    lines = g.read().splitlines()

for devices in all_devices:
    net_connect = ConnectHandler(**devices)
    output = net_connect.send_config_set(lines)
    print(output)

Solution

  • Use try/except to skip the device if you get a timeout.

    for devices in all_devices:
        try:
            net_connect = ConnectHandler(**devices)
            output = net_connect.send_config_set(lines)
        except socket.timeout:
            print(f"Timeout for {devices}, skipping")
            continue