我想获取一个pcap文件的UDP流,获取原始数据并保存到.ts文件。我现在可以在 Wireshark 中做到这一点:
analyze->follow->UDP stream->show and save data as raw->save as->video.ts
.
如何用 Python 编写脚本来做同样的事情?
可以使用
tshark
(wireshark-cli)(或 dpkt 或其他工具)
但是这里有一个用python的
scapy
的解决方案。
(原谅我污染的命名空间)
from scapy.all import *
import io
ts_pcap = sniff(offline='ts_sessions.pcap', filter='udp') # for example...
for five_tuple, session_packets in ts_pcap.sessions().items(): # going over each session
session_buffer = io.BytesIO() # instead of writing each packet to disk, let's save each session's payload to memory. depending on the size of the streams this might be a bad idea.
for packet in session_packets:
session_buffer.write(bytes(packet['UDP'].payload)) # extracting udp payload from each packet, as bytes.
exracted_ts_stream_name = five_tuple.replace(">", "_").replace(":","-") + ".ts"
session_buffer.seek(0) # otherwise the pointer is at the end of the buffer
with open(exracted_ts_stream_name, "wb") as f:
f.write(session_buffer.read())