如何在watchdog监控到新文件时以线程运行pcap转csv脚本
实现多线程并行处理PCAP转CSV的Watchdog监控脚本
核心修改思路
- 引入Python标准库
threading,为每个新创建的PCAP文件单独启动线程执行转换操作,实现并行处理 - 修复原代码中通过
glob遍历找最新文件的逻辑缺陷,直接利用Watchdog事件对象获取触发事件的文件路径 - 修正字符串格式化语法错误,同时增加文件类型判断,只处理PCAP文件
修改后的完整代码
import os import time import threading from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler def on_created(event): # 忽略目录创建事件,只处理文件 if not event.is_directory: file_path = event.src_path # 只处理pcap格式文件 if file_path.endswith('.pcap'): # 启动线程执行转换 threading.Thread(target=create_csv, args=(file_path,)).start() def create_csv(file_path): output_path = f"{file_path}.csv" # 构造tshark命令,给路径加引号避免空格问题 cmd = f'tshark -r "{file_path}" -Y sip -E header=y -E separator=, -T fields -e sip.From -e sip.To > "{output_path}"' print(f"开始转换文件: {file_path}") os.system(cmd) print(f"文件转换完成: {output_path}") if __name__ == "__main__": event_handler = FileSystemEventHandler() event_handler.on_created = on_created # 替换为你的监控路径 monitor_path = 'path/to/pcap/files' observer = Observer() observer.schedule(event_handler, monitor_path, recursive=True) observer.start() try: while True: time.sleep(1) except KeyboardInterrupt: observer.stop() print("监控已停止") observer.join()
关键修改说明
- 多线程实现:在
on_created中,通过threading.Thread创建新线程,将create_csv作为目标函数并传入文件路径参数,调用start()启动线程,这样每个文件转换操作都在独立线程中执行,不会阻塞Watchdog的监控主进程。 - 事件对象直接获取文件路径:原代码通过
glob遍历目录找最新文件的方式不可靠(可能同时有多个文件创建时出错),直接使用event.src_path可以准确拿到触发当前事件的文件路径。 - 文件类型过滤:增加了
endswith('.pcap')判断,避免非PCAP文件触发转换逻辑。 - 语法错误修正:将原代码中错误的
f('...')格式化为正确的f"..."字符串,同时给文件路径加上引号,避免路径含空格时命令执行失败。
内容的提问来源于stack exchange,提问作者Armageddon
相关产品推荐
相关产品推荐

