1 代码在经过多次验证无问题,如在使用中报错,请修改网络设备参数,以及Python代码的缩进格式 from netmiko import ConnectHandler import datetime import threading import concurrent.futures import os # 假设您的IP地址列表保存在一个名为"ping_successes_20240228_101758.txt"的文本文件中,每行一个IP地址 ip_file = "ping_successes_20240228_101758.txt" # 从环境变量或配置文件读取敏感信息 USERNAME = os.environ.get("NETMIKO_USERNAME", "根据实际情况填写") PASSWORD = os.environ.get("NETMIKO_PASSWORD", "根据实际情况填写") def save_output_to_file(ip): try: # 获取当前时间,用于文件名 now = datetime.datetime.now().strftime("%Y%m%d%H%M%S") # 添加进程ID以确保文件名唯一 process_id = str(os.getpid()) # 构建文件名,格式为 IP地址_当前时间_进程ID.txt filename = f"{ip}_{now}_{process_id}.txt" # 设备连接参数 device = { 'device_type': 'hp_comware', # 根据您的设备类型修改 'ip': ip, 'username': USERNAME, 'password': PASSWORD, 'global_delay_factor': 0.1, # 可选的,用于调整所有延迟的乘数 'timeout': 60, # 设置超时时间 # 其他必要的连接参数... } # 使用 with 语句确保连接被正确关闭 with ConnectHandler(**device) as connection: try: output = connection.send_command('display cur') # 确保命令与您的设备兼容 except Exception as e: # 只写入失败的 IP 地址到 fail.txt with open("fail.txt", 'a') as fail_file: fail_file.write(f"{ip}\n") print(f"Error executing command on {ip}: {e}") return # 将输出写入到文件中(这里您可能需要根据实际情况处理output) with open(filename, 'w') as file: file.write(output) except Exception as e: # 只写入失败的 IP 地址到 fail.txt with open("fail.txt", 'a') as fail_file: fail_file.write(f"{ip}\n") print(f"Error connecting to {ip}: {e}") # 读取IP地址列表 with open(ip_file, 'r') as file: ip_addresses = file.read().splitlines() # 使用线程池限制并行线程数量 with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor: # 设置最大工作线程数为10 # 为每个IP地址创建一个线程并提交到线程池 for ip in ip_addresses: executor.submit(save_output_to_file, ip) print("All tasks submitted to the thread pool.")
自动备份H3C网络设备配置(dis cur),不能登录的设备地址写入fail.txt.
于 2024-02-28 11:37:26 首次发布