关于Tshark实时捕获网络流量并输出JSON文件的技术问题
Let's fix both of your issues step by step—getting JSON output and making the file usable while Tshark runs, plus trimming down the file size.
1. Output JSON Format & Real-Time File Access
Your original command uses -w which writes binary PCAP data, not JSON. To output JSON and ensure the file is readable while Tshark is running, use these parameters:
tshark -i 4 -l -T json > /your/specified/folder/capture.json
Parameter Breakdown:
-i 4: Keeps your original interface selection (adjust if needed)-l: Enables line buffering—this forces Tshark to write each JSON entry to the file immediately instead of waiting for a full buffer. Now you can opencapture.jsonand see live data while the capture runs.-T json: Tells Tshark to output packet data in JSON format instead of binary PCAP.> /your/specified/folder/capture.json: Redirects the JSON output directly to your target file.
2. Reduce File Size
JSON is text-based, so it can get large if you capture all traffic. Here are two effective ways to shrink the output:
Option A: Filter Unwanted Traffic
Use the -Y flag to capture only the traffic you care about (e.g., HTTP/HTTPS, DNS, etc.). This cuts down the number of entries in your JSON file drastically:
# Capture only HTTP and HTTPS traffic tshark -i 4 -l -T json -Y "http or ssl" > /your/specified/folder/capture_filtered.json
You can use any Wireshark display filter here—examples include dns for DNS queries, tcp.port == 22 for SSH, or ip.src == 192.168.1.100 for traffic from a specific IP.
Option B: Capture Only Specific Fields
If you don't need every detail of each packet, use -e to specify exactly which fields to include in the JSON. This reduces each entry's size:
# Capture only source/dest IPs, TCP ports, and HTTP request methods tshark -i 4 -l -T json -e ip.src -e ip.dst -e tcp.srcport -e tcp.dstport -e http.request.method > /your/specified/folder/capture_minimal.json
Advanced: Split Files by Time/Size
For long-running captures, split the JSON into smaller, time-stamped files using a simple shell script. This prevents any single file from getting too large:
while true; do # Generate a unique timestamp for each file timestamp=$(date +%Y%m%d_%H%M%S) # Capture for 5 minutes (300 seconds) then rotate to a new file tshark -i 4 -l -T json -Y "http or ssl" -a duration=300 > /your/specified/folder/capture_$timestamp.json done
Run this script in the background, and it will create a new JSON file every 5 minutes with a timestamp (e.g., capture_20240520_143000.json).
内容的提问来源于stack exchange,提问作者Ahmed Adnane A'mil

