I am using the file capture API of pyshark like this.
#!/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())
But now, I have another use case where the file content can be made available to me only as an array of bytes, or as UploadFile class of FastAPI.
Basically, the user (frontend) will upload the pcapng file and then I need to read it as an array of packet, getting the same capture object I can get from a pcapng file stored locally. If necessary, I can read the file content as byte in memory as well, like this.
file: UploadFile = File(default=...) # Obtained from front-end
file_content:bytes=await file.read()
So how to get the capture object from the user uploaded file? I had the idea of dumping the file_content on disk as a temporary file and then reading it via FileCapture
, which is clearly suboptimal and bug prone. But even that is not working.
So is there a way to get the capture object directly from in-memory bytes via pyshark? I tried:
capture=ps.InMemCapture(file_content) # Failed because capture is of length 0
but it failed to read any packet.