请求协助:扫描日志提取指定dst_ip相关字段(CMD/脚本方案)
方案1:Windows CMD批处理实现
适合无额外软件安装需求的场景,直接在Windows命令行执行。
步骤说明
- 准备目标IP列表:新建
target_ips.txt文件,将50个目标IP每行写入一个,示例:
10.3.2.1 192.168.0.100 ...
- 新建批处理文件(比如
process_log.bat),复制以下代码,替换日志文件路径为实际路径:
@echo off setlocal enabledelayedexpansion :: 配置路径,替换为实际文件路径 set "logfile=D:\path\to\your\logfile.log" set "ip_list=target_ips.txt" set "output=log_result.csv" :: 初始化输出文件,写入表头 echo dst_ip,protocol,dst_port > %output% :: 遍历所有匹配目标IP的日志行 for /f "tokens=*" %%a in ('findstr /g:%ip_list% %logfile%') do ( set "line=%%a" :: 提取dst_ip字段 for /f "tokens=2 delims==" %%b in ('echo !line! ^| findstr /i "dst_ip="') do set "dst_ip=%%b" :: 提取protocol字段并去除引号 for /f "tokens=2 delims==" %%b in ('echo !line! ^| findstr /i "protocol="') do ( set "proto=%%b" set "proto=!proto:"=!" ) :: 提取dst_port字段 for /f "tokens=2 delims==" %%b in ('echo !line! ^| findstr /i "dst_port="') do set "dst_port=%%b" :: 写入结果到输出文件 echo !dst_ip!,!proto!,!dst_port! >> %output% ) echo 处理完成,结果已保存到 %output% pause
- 双击运行
process_log.bat,结果会生成在log_result.csv文件中。
注意事项
- 若日志文件编码为UTF-8带BOM,可能导致findstr解析异常,可先用记事本另存为ANSI编码后再处理。
- 大文件处理速度略慢,但能满足需求。
方案2:Python脚本实现
处理大文件效率更高,字段提取更稳定,适合能安装Python的场景。
步骤说明
- 安装Python:从官网下载并安装Python(勾选"Add Python to PATH")。
- 新建脚本文件(比如
process_log.py),复制以下代码,修改目标IP列表和日志路径:
import re # 替换为你的50个目标IP target_ips = { "10.3.2.1", "192.168.0.100", # 添加更多IP... } # 替换为实际日志文件路径和输出文件路径 log_file = "D:\\path\\to\\your\\logfile.log" output_file = "log_result.csv" # 匹配字段的正则表达式,适配日志格式 field_pattern = re.compile(r'dst_ip=([\d.]+).*?protocol="?([^"\s]+)"?.*?dst_port=(\d+)') with open(log_file, 'r', encoding='utf-8', errors='ignore') as input_file, \ open(output_file, 'w', encoding='utf-8') as output_file: # 写入表头 output_file.write("dst_ip,protocol,dst_port\n") # 逐行读取日志文件,避免内存占用过高 for line in input_file: # 先提取dst_ip判断是否在目标列表 ip_match = re.search(r'dst_ip=([\d.]+)', line) if ip_match and ip_match.group(1) in target_ips: # 提取三个目标字段 match = field_pattern.search(line) if match: dst_ip, protocol, dst_port = match.groups() output_file.write(f"{dst_ip},{protocol},{dst_port}\n") print(f"处理完成!结果已保存到 {output_file}")
- 打开命令行,进入脚本所在目录,执行命令:
python process_log.py
注意事项
- 脚本采用逐行读取,即使是1GB的日志文件也不会占用过多内存。
- 正则表达式适配了protocol字段带引号或不带引号的情况,兼容性更好。
内容的提问来源于stack exchange,提问作者wannabemssp
相关产品推荐
相关产品推荐

