Python自动备份优化后—取消了进程ID

本文介绍如何使用Python的NetMiko库连接并控制多个网络设备,通过线程池并发执行displaycur命令,将结果保存到文件,同时处理连接失败情况。
摘要由CSDN通过智能技术生成

from netmiko import ConnectHandler
import datetime
import threading
import concurrent.futures
import os

# 假设您的IP地址列表保存在一个名为"ips.txt"的文本文件中,每行一个IP地址
ip_file = "ips.txt" # 确保此文件存在并包含IP地址

# 从环境变量或配置文件读取敏感信息
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")

# 构建文件名,格式为 IP地址_当前时间.txt
filename = f"{ip}_{now}.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:
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 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:
# 为每个IP地址创建一个线程并提交到线程池
for ip in ip_addresses:
executor.submit(save_output_to_file, ip)

print("All tasks submitted to the thread pool.")

  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值