如何使用Pyshark直接从内存读取.pcapng文件内容(FastAPI场景)
问题:Pyshark如何从内存字节解析pcapng文件?
原本使用Pyshark读取本地pcapng文件的代码如下:
#!/usr/bin/env python3 # encoding:utf-8 import pyshark as ps filename: str = 'some_file.pcapng' with ps.FileCapture(input_file=filename) as capture: print(capture[0].pretty_print())
现在场景变更为用户通过前端上传pcapng文件,只能通过FastAPI的UploadFile类或字节数组获取文件内容,读取内存字节的方式如下:
file: UploadFile = File(default=...) # 从前端获取 file_content:bytes=await file.read()
需要获取和读取本地文件时相同的capture对象来解析数据包数组。尝试过将字节写入临时文件再用FileCapture读取,但该方式低效且出错;也试过ps.InMemCapture(file_content),但捕获内容长度为0,无法读取数据包。请问是否可以通过Pyshark直接从内存字节获取capture对象?
解决方案
可以通过将字节内容转换为类文件对象,再传入Pyshark.FileCapture来实现,无需写入临时文件。FileCapture不仅支持传入文件名,还支持任何实现了文件接口(如read()方法)的对象,包括io.BytesIO。
具体代码示例
import pyshark as ps import io from fastapi import FastAPI, File, UploadFile app = FastAPI() @app.post("/parse-pcap/") async def parse_pcap(file: UploadFile = File(...)): # 读取上传文件的字节内容 file_content = await file.read() # 将字节转为类文件对象 file_like_obj = io.BytesIO(file_content) # 使用FileCapture解析内存中的pcapng内容 with ps.FileCapture(input_file=file_like_obj) as capture: packets = list(capture) # 示例:打印第一个包的格式化信息 if packets: print(packets[0].pretty_print()) return {"packet_count": len(packets)}
关键说明
ps.InMemCapture的设计用途是实时捕获网络流量并存储到内存,而非解析已有的pcap格式字节数据,因此之前的尝试会失败。io.BytesIO将字节数组封装为类文件对象,完全兼容FileCapture的输入要求,实现内存级别的高效解析。
内容的提问来源于stack exchange,提问作者Della
相关产品推荐
相关产品推荐

