Python 批量配置网络设备:从 Excel 读取列表到并发执行

Aria
Aria
发布时间:2026-12-06 | 721人浏览过
原创

使用 pandas 读取 Excel 配置列表,结合 concurrent.futures.ThreadPoolExecutor 实现并发登录与下发。核心在于将设备连接逻辑封装为独立函数,并通过线程池控制并发数以避免资源耗尽。

Python 批量配置网络设备:从 Excel 读取列表到并发执行

Excel 数据解析与字段映射

先确保 Excel 文件包含 ip, username, password, commands 等列。使用 pandas.read_excel 加载数据,并将 commands 列从字符串转换为列表格式,以便后续遍历执行。

Python 批量配置网络设备:从 Excel 读取列表到并发执行

在实际操作中,Excel 中的命令通常以换行符分隔的长字符串存储。解析时需按 \n 分割并过滤空行。同时,需对 IP 地址进行有效性校验,排除无效条目。若存在多张工作表,可通过 sheet_name 参数指定目标表。

并发执行框架搭建

程序应放在 batch_config.py 中。运行命令为 python batch_config.py config.xlsx。成功标志是控制台输出所有设备的执行结果汇总,无报错退出。

Python 批量配置网络设备:从 Excel 读取列表到并发执行

import pandas as pd
from concurrent.futures import ThreadPoolExecutor, as_completed
import time

def parse_commands(cmd_str):
    if not cmd_str or pd.isna(cmd_str):
        return []
    return [c.strip() for c in str(cmd_str).split('\n') if c.strip()]

def execute_device_task(device_info):
    ip = device_info['ip']
    username = device_info['username']
    password = device_info['password']
    commands = parse_commands(device_info.get('commands', ''))
    
    # 模拟网络操作耗时
    time.sleep(0.5)
    
    results = []
    try:
        for cmd in commands:
            # 此处替换为实际 netmiko 或 paramiko 连接代码
            # result = connect_and_run(ip, username, password, cmd)
            result = f"Executed {cmd} on {ip}"
            results.append(result)
        status = 'success' if results else 'no_commands'
    except Exception as e:
        status = 'error'
        results = [str(e)]
    
    return {
        'ip': ip,
        'status': status,
        'outputs': results
    }

def main(excel_path):
    df = pd.read_excel(excel_path)
    devices = df.to_dict('records')
    
    max_workers = 10
    all_results = []
    
    with ThreadPoolExecutor(max_workers=max_workers) as executor:
        future_to_dev = {executor.submit(execute_device_task, dev): dev for dev in devices}
        for future in as_completed(future_to_dev):
            try:
                res = future.result()
                all_results.append(res)
                print(f"Device {res['ip']} completed: {res['status']}")
            except Exception as exc:
                print(f"Task failed: {exc}")
    
    return all_results

if __name__ == '__main__':
    import sys
    if len(sys.argv) > 1:
        results = main(sys.argv[1])
    else:
        print("Please provide excel file path")

程序输出显示每个设备的执行状态。若 Excel 中某行 commands 为空,状态将为 no_commands。修改并发数 max_workers 可观察执行速度变化,但过高会导致连接错误。确保 Excel 路径正确且包含必要列。

采用线程池而非进程池,因为网络 I/O 等待时间长,线程切换开销更小。设置最大并发数为 10,防止同时建立过多连接导致目标设备或本地系统资源过载。每个任务提交后,立即获取 Future 对象以便后续收集结果。

异常处理与日志记录

当某台设备连接失败时,线程池默认会抛出异常。需要在 execute_device_task 中捕获具体错误,如超时或认证失败,并返回结构化错误信息,避免单个设备故障中断整个批量任务。

建议在代码中加入简单的日志记录,将关键步骤写入文件或控制台。对于网络操作,可设置重试机制,例如在捕获到特定网络异常时自动重试一次。最终输出的结果列表中,失败的设备状态标记为 error,并附带错误详情,方便运维人员后续排查。

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表