pythonpython-3.xcisco-ios

Open Dictionary File in Python


I am trying to develop a Python script that will log into hundreds of Cisco IOS devices and configure them. The issue I am running into is that I do not want to define the device dictionary in the script itself, but have the script refer to a file (YAML?) and loop through the devices in the file. The script looks like this:

from netmiko import ConnectHandler

R1 = {
    'device_type': 'cisco_ios',
    'ip': '192.168.122.71',
    'username': 'admin',
    'password': 'cisco'
}

R2 = {
    'device_type': 'cisco_ios',
    'ip': '192.168.122.82',
    'username': 'admin',
    'password': 'cisco'
}


with open('snmp_configs.txt') as f:
    lines = f.read().splitlines()
print (lines)

all_devices = [R1, R2]

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

As you can see I have R1 and R2 defined using dictionaries, but I don't want to add hundreds of device dictionaries in the script itself.


Solution

  • You can use either JSON or YAML format to store devices list and load the file in the script.

    To use JSON format, create a file with .json extension, e.g. devices.json with following content:

    [
       {
          "device_type":"cisco_ios",
          "ip":"192.168.122.71",
          "username":"admin",
          "password":"cisco"
       },
       {
          "device_type":"cisco_ios",
          "ip":"192.168.122.82",
          "username":"admin",
          "password":"cisco"
       }
    ]
    

    To use YAML, do the same but this time with .yaml extension, e.g. devices.yaml with below content. To load this file you will need to install the PyYAML package (e.g. pip install PyYAML)

    - device_type: cisco_ios
      ip: 192.168.122.71
      username: admin
      password: cisco
    - device_type: cisco_ios
      ip: 192.168.122.82
      username: admin
      password: cisco
    

    You can load the two files in the script like this:

    import json
    import yaml
    
    # Load the json file
    with open("devices.json") as f:
        all_devices = json.load(f)
        print(all_devices)
    
    # Load the YAML file
    with open("devices.yaml") as f:
        all_devices = yaml.safe_load(f)
        print(all_devices)
    
    for device in all_devices:
        print(device)