1、 需对公司所有网络设备进行定期备份
2、不能登录设备,会将登录失败原因写入fail.txt文档
3、和另外一篇类似,但是这里会在备份配置文件加了进程ID,我目前的环境中不需要。
Python脚本如下
from netmiko import ConnectHandler import datetime import threading import concurrent.futures import os # 假设您的IP地址列表保存在一个名为"ips.txt"的文本文件中,每行一个IP地址 ip_file = "ping_successes_20240227_145218.txt" # 从环境变量或配置文件读取敏感信息 USERNAME = os.environ.get("NETMIKO_USERNAME", "yangwb") PASSWORD = os.environ.get("NETMIKO_PASSWORD", "Ywb@098765") 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: # 如果发送命令失败,将异常信息写入失败文件 with open("fail.txt", 'a') as fail_file: fail_file.write(f"{ip}: {str(e)}\n") return # 将输出写入到文件中(这里您可能需要根据实际情况处理output) with open(filename, 'w') as file: file.write(output) except Exception as e: # 如果连接失败,将异常信息写入失败文件 with open("fail.txt", 'a') as fail_file: fail_file.write(f"{ip}: {str(e)}\n") print(f"Error connecting to or executing command on {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.")