You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python新增类同chain的chain2字典,实现iptables日志转Excel

我清楚你要做的是优化那段处理多节点iptables日志的Python代码——新增了和原有chain字典结构一致的chain2字典,需要把相关描述文本中文化,同时严格保留iptables、Chain、ACCEPT这类技术术语,还要保证业务逻辑丝毫不差。下面是调整后的完整方案:

需求拆解与核心原则
  • 严格保留所有iptables技术术语(如Chain、ACCEPT、REJECT、INPUT等)的英文原称,避免专业领域的理解混淆
  • 对chain、chain2字典中的描述性文本进行中文化适配,让国内运维人员更易理解
  • 完全保留原有代码的核心逻辑:多节点日志读取、Chain规则解析、Excel导出功能
调整后的完整代码
import re
import pandas as pd
from pathlib import Path

# 定义规则链配置(已中文化描述)
chain = {
    "name": "INPUT",
    "description": "入站流量核心规则链",
    "log_pattern": r"IN=(\w+) OUT=(\w+) MAC=([\w:]+) SRC=(\d+\.\d+\.\d+\.\d+) DST=(\d+\.\d+\.\d+\.\d+) PROTO=(\w+) .*?(ACCEPT|REJECT|DROP)"
}

chain2 = {
    "name": "CUSTOM_FORWARD",
    "description": "自定义转发扩展规则链",
    "log_pattern": r"IN=(\w+) OUT=(\w+) MAC=([\w:]+) SRC=(\d+\.\d+\.\d+\.\d+) DST=(\d+\.\d+\.\d+\.\d+) PROTO=(\w+) .*?(ACCEPT|REJECT|DROP)"
}

def parse_iptables_log(log_file_path, chain_config):
    """解析单个节点的iptables日志文件"""
    parsed_records = []
    pattern = re.compile(chain_config["log_pattern"])
    
    with open(log_file_path, "r", encoding="utf-8") as f:
        for line in f:
            match = pattern.search(line)
            if match:
                parsed_records.append({
                    "节点名称": Path(log_file_path).stem,
                    "Chain名称": chain_config["name"],
                    "规则链描述": chain_config["description"],
                    "入站网卡": match.group(1),
                    "出站网卡": match.group(2),
                    "MAC地址": match.group(3),
                    "源IP": match.group(4),
                    "目标IP": match.group(5),
                    "协议": match.group(6),
                    "动作": match.group(7)
                })
    return parsed_records

def export_to_excel(records, output_path):
    """将解析结果导出为Excel表格"""
    df = pd.DataFrame(records)
    df.to_excel(output_path, index=False, encoding="utf-8")
    print(f"解析结果已成功导出至:{output_path}")

if __name__ == "__main__":
    # 多节点日志文件路径集合
    log_files = [
        "/var/log/iptables/node1.log",
        "/var/log/iptables/node2.log",
        "/var/log/iptables/node3.log"
    ]
    
    # 解析所有规则链的日志
    all_records = []
    for log_file in log_files:
        all_records.extend(parse_iptables_log(log_file, chain))
        all_records.extend(parse_iptables_log(log_file, chain2))
    
    # 导出到Excel
    export_to_excel(all_records, "iptables_规则解析结果.xlsx")
关键调整说明
  1. 规则链描述中文化:chain和chain2的description字段已替换为中文描述,同时保留name字段的iptables标准链名(如INPUT、CUSTOM_FORWARD)
  2. Excel表头适配:将原有的英文表头调整为中文表头(如节点名称),但保留Chain名称中的Chain术语,兼顾专业准确性和可读性
  3. 逻辑完全兼容:所有日志解析、多节点遍历、Excel导出的核心逻辑未做任何修改,确保原有功能不受影响

内容的提问来源于stack exchange,提问作者Romain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:57:23