Python实现多文本文件中指定IP相关规则块的信息提取
Python 提取包含指定IP的防火墙规则块信息
直接上可运行的代码,能遍历所有st.txt文件,筛选出包含169.176.39.0/24的规则块,并提取你需要的信息:
import os TARGET_IP = "169.176.39.0/24" def parse_rule_block(block_lines): # 初始化提取的信息 combo_tuple = "" source_ips = [] dest_ips = [] ports = [] for line in block_lines: line = line.strip() if not line: continue # 提取Combination和Tuple编号 if line.startswith("Combination"): combo_tuple = line.split(":", 1)[1].strip() # 提取Source Groups里的IP elif "Source Groups" in line: ip_part = line.split(":", 1)[1].strip().strip("[]") if ip_part: source_ips = [ip.strip() for ip in ip_part.split(",")] # 提取Destination Group里的IP elif "Destination Group" in line: ip_part = line.split(":", 1)[1].strip().strip("[]") if ip_part: dest_ips = [ip.strip() for ip in ip_part.split(",")] # 提取端口信息 elif any(keyword in line for keyword in ["Port", "Destination Port"]): port_part = line.split(":", 1)[1].strip() if port_part: ports = [p.strip() for p in port_part.split(",")] return { "combination_tuple": combo_tuple, "source_ips": source_ips, "dest_ips": dest_ips, "ports": ports } def process_st_file(file_path): matched_blocks = [] with open(file_path, "r", encoding="utf-8") as f: lines = f.readlines() current_block = [] for line in lines: # 遇到新的Combination行,先处理之前的块 if line.strip().startswith("Combination"): if current_block: if TARGET_IP in " ".join(current_block): parsed = parse_rule_block(current_block) matched_blocks.append(parsed) current_block = [] current_block.append(line) else: current_block.append(line) # 处理最后一个块 if current_block and TARGET_IP in " ".join(current_block): parsed = parse_rule_block(current_block) matched_blocks.append(parsed) return matched_blocks def main(): # 遍历当前目录及子目录下所有st.txt文件 for root, dirs, files in os.walk("."): for file in files: if file == "st.txt": file_path = os.path.join(root, file) print(f"=== 处理文件: {file_path} ===") matched = process_st_file(file_path) if not matched: print("无匹配规则块\n") continue # 按指定格式输出 for idx, block in enumerate(matched, 1): print(f"规则块 {idx}:") print(f" Combination&Tuple: {block['combination_tuple']}") print(f" Source Groups IP: {', '.join(block['source_ips'])}") print(f" Destination Group IP: {', '.join(block['dest_ips'])}") print(f" 端口信息: {', '.join(block['ports'])}\n") if __name__ == "__main__": main()
代码说明
- 遍历文件:用
os.walk自动扫描所有子目录里的st.txt,无需手动指定路径 - 分割规则块:以
Combination开头的行作为规则块起始,每遇到新的起始行就处理完上一个块 - 筛选目标IP:将块内所有内容拼接成字符串,检查是否包含目标IP
- 提取字段:针对规则块内的关键行,按字符串分割提取对应信息,适配常见规则格式;如果你的文件格式有特殊之处,直接修改
parse_rule_block里的判断逻辑即可 - 输出格式:目前是分文件、分规则块的清晰排版,你可以根据需求调整成写入文件或其他格式
注意事项
如果你的st.txt字段格式和代码假设的不同(比如Source Groups不是[IP1,IP2]格式),直接修改parse_rule_block里对应字段的处理代码,调整分割符或改用正则匹配都可以。
内容的提问来源于stack exchange,提问作者Noah
相关产品推荐
相关产品推荐

