I want to get the UDP stream of a pcap file, get the raw data and save to a .ts file. I now i can do that in Wireshark doing: analyze->follow->UDP stream->show and save data as raw->save as->video.ts
.
How can i make a script in Python for doing the same thing?
It could probably be done using tshark
(wireshark-cli) (or dpkt or other tools)
But here's a solution with python's scapy
.
(forgive my polluted namespace)
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())