Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Redirect output into multiple files

I have a script in that script we have multiple hostnames and trying to print the command of the output into multiple files i.e each hostname has different output, want to print that in multiple files.

I have the code that is printing all output in a single txt file, Please find the attached code below.

 from netmiko import ConnectHandler
import getpass
import sys
from datetime import datetime


passwd = getpass.getpass('Please enter the password: ')

my_devices = ['192.1.1.1', '192.1.1.2', '192.1.1.3'] 
device_list = list() 

for device_ip in my_devices:
    device = {
        "device_type": "cisco_ios",
        "host": device_ip,
        "username": "root",
        "password": passwd, # Log in password from getpass
        "secret": passwd # Enable password from getpass
    }
    device_list.append(device)

print(device_list) #list of dictionaries

for each_device in device_list:
    connection = ConnectHandler(**each_device)
    connection.enable()
    print(f'Connecting to {each_device["host"]}')
    output = connection.send_command('show configuration | display set')
    sys.stdout = open((datetime.today()).strftime('%Y%m%d')+ "_" + "switch_config.txt", 'a')
    print(output)

    print(f'Closing Connection on {each_device["host"]}')
    connection.disconnect()

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Just open another file for each.

for each_device in device_list:
    connection = ConnectHandler(**each_device)
    connection.enable()
    print(f'Connecting to {each_device["host"]}')
    output = connection.send_command('show configuration | display set')
    with open((datetime.today()).strftime('%Y%m%d')+ "_" + each_device["host"] + "_switch_config.txt", 'a') as filehandle:
        filehandle.write(output + "\n")
    print(f'Closing Connection on {each_device["host"]}')
    connection.disconnect()

This avoids the ugly messing with sys.stdout (which would also write your diagnostic messages to the file, obviously) and you didn’t reveal what the file should be called and whether or not it should be overwritten, so I had to guess.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading