簡體   English   中英

將output重定向到多個文件中

[英]Redirect output into multiple files

我在該腳本中有一個腳本,我們有多個主機名,並嘗試將 output 的命令打印到多個文件中,即每個主機名都有不同的 output,想要在多個文件中打印。

我有在單個 txt 文件中打印所有 output 的代碼,請在下面找到附加代碼。

 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()

只需為每個文件open另一個文件。

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()

這避免了sys.stdout的丑陋混亂(顯然,這也會將您的診斷消息寫入文件)並且您沒有透露應該調用什么文件以及是否應該覆蓋它,所以我不得不猜測。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM