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()
CodePudding user response:
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.