自动备份H3C网络设备配置(dis cur),不能登录的设备地址写入fail.txt.

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.")
  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值