[Python] Python Script Processing Order with JSON Input

Discussão em 'Python' iniciado por Stack, Setembro 12, 2025.

  1. Stack

    Stack Membro Participativo

    I'm working through some changes to a script I had working. I have changed the input of an IP address file to a json file so that I can include key details like the hostname and maybe later on more details if needed.

    After a lot of crazy results I got the script to finish without error and somewhat work. I'm uncertain though what is causing my current issue and how to fix it.

    I have one test router, TACOSPLEASE-R1 (10.255.221.11), and it works. The second router, TACOSPLEASE-R1 (10.255.221.12), does not exist for error handling purposes.

    When I was using a text file for IP address input the script worked fine. R1 was backed up and R2 failed to connect as expected.

    With the json input I'm getting some weird results. The output is saying R1 doesn't work and R2 does. I think the json keys are mixed up but I'm unsure how to fix it so that R1/10.255.221.11 always stay together and so on.

    Results below

    brian@tacosplease-scripts:~/scripts$ python3 junos-backups.py
    Config backups started at: 20250912-15:35:41

    Connecting to device: TACOSPLEASE-R1
    Error connecting to TACOSPLEASE-R1: Either ip or host must be set

    Connecting to device: TACOSPLEASE-R2
    Connected to TACOSPLEASE-R2
    Configuration backed up to /home/brian/backups/TACOSPLEASE-R2-Config-Backup-20250912-15:35:41.txt
    Disconnected from device.
    Config backups completed at: 20250912-15:35:41
    brian@tacosplease-scripts:~/scripts$



    json file is below

    {
    "hosts": [
    {
    "hostname": "TACOSPLEASE-R1",
    "address": "10.255.221.11"
    },
    {
    "hostname": "TACOSPLEASE-R2",
    "address": "10.255.221.12"
    }
    ]
    }


    Script is below

    from netmiko import ConnectHandler
    from datetime import datetime
    from os import getenv
    import json

    # Open json file to read password
    with open('/home/brian/script-variables/passwords.json', 'r') as pwd_file:
    pwd_data = json.load(pwd_file)

    juniper_password = pwd_data['password']


    # netmiko variables for juniper
    juniper_device = {
    'device_type': 'juniper_junos',
    'username': 'root',
    'password': juniper_password,
    }


    # Get the current date/time and format it for our filenames
    current_datetime = datetime.now()
    formatted_datetime = current_datetime.strftime("%Y%m%d-%H:%M:%S")


    # Print the start time
    print("Config backups started at:", formatted_datetime)


    # Open file to read IP addreses from
    with open('/home/brian/script-variables/devices.json', 'r') as dvc_file:
    device_file = json.load(dvc_file)
    json_device_file = device_file["hosts"]

    # Loop through the devices json file so that we can connect to every device
    for value in json_device_file:

    print(f"\nConnecting to device: {value['hostname']}")

    # Create a dictionary for the current device's connection
    current_device = juniper_device.copy()
    juniper_device["host"] = value['address']

    try:
    net_connect = ConnectHandler(**current_device)
    print(f"Connected to {value['hostname']}")

    # Pull the configuration in 'set' format
    config_output = net_connect.send_command('show configuration | display set', use_textfsm=False)

    # Set the backup file name
    backup_filename = f"/home/brian/backups/{value['hostname']}-Config-Backup-{formatted_datetime}.txt"

    # Save the configuration to a file
    with open(backup_filename, 'w') as device_file:
    device_file.write(config_output)
    print(f"Configuration backed up to {backup_filename}")

    except Exception as e:
    print(f"Error connecting to {value['hostname']}: {e}")

    finally:
    if 'net_connect' in locals() and net_connect.is_alive():
    net_connect.disconnect()
    print("Disconnected from device.")


    # Print the finish time
    print("Config backups completed at:", formatted_datetime)

    Continue reading...

Compartilhe esta Página