基于Tshark的Python流量捕获脚本开发需求:生成pcap与csv文件
Got it, let's break down how to replicate your tcpdump capture logic with Tshark and Python, while also generating that required CSV file. Here's a complete, working solution with explanations:
Solution Overview
We'll use Python's built-in subprocess module to launch Tshark with parameters that mirror your tcpdump rotation behavior, plus configure Tshark to export the exact CSV fields you need.
Prerequisites
- Tshark installed on your system (it's part of Wireshark; make sure it's in your
PATHor use the full path like/usr/bin/tshark) - Python 3.x (any recent version works)
- Root/sudo privileges (required for network traffic capture)
Complete Python Script
import subprocess import signal import sys def signal_handler(sig, frame): """Handle Ctrl+C to stop the capture gracefully""" print("\nStopping traffic capture...") proc.terminate() sys.exit(0) if __name__ == "__main__": # Configuration - match your original tcpdump settings pcap_output_prefix = "normaltraffic" max_rotation_files = 5 max_file_size_mb = 500 # Tshark uses KB for file size, so convert MB to KB max_file_size_kb = max_file_size_mb * 1000 # Capture interface - use "any" for all interfaces, or specify e.g., "eth0", "wlan0" capture_interface = "any" # Build the Tshark command tshark_command = [ "tshark", # Capture interface "-i", capture_interface, # File rotation settings (matches tcpdump -W 5 -C 500) "-b", f"filesize:{max_file_size_kb}", "-b", f"files:{max_rotation_files}", # Output pcap files (Tshark will append _00001.pcap, _00002.pcap, etc.) "-w", pcap_output_prefix, # CSV export configuration "-T", "fields", "-E", "separator=,", "-E", "header=y", "-E", "quote=d", # Quote fields with double quotes to handle commas in "Info" # Specify the exact fields you need (matches Wireshark's default CSV columns) "-e", "_ws.col.No.", "-e", "_ws.col.Time", "-e", "_ws.col.Source", "-e", "_ws.col.Destination", "-e", "_ws.col.Protocol", "-e", "_ws.col.Length", "-e", "_ws.col.Info", ] # Open the CSV file for writing with open("traffic_output.csv", "w") as csv_file: # Launch Tshark process proc = subprocess.Popen( tshark_command, stdout=csv_file, stderr=subprocess.PIPE, text=True ) # Set up signal handler for Ctrl+C signal.signal(signal.SIGINT, signal_handler) # Print status info print(f"Starting traffic capture...") print(f"PCAP files will be saved as {pcap_output_prefix}_*.pcap") print(f"Max files: {max_rotation_files}, Max size per file: {max_file_size_mb}MB") print(f"CSV output saved to traffic_output.csv") print("Press Ctrl+C to stop capture.\n") # Wait for the process to finish (or be terminated) proc.wait()
Key Details Explained
- File Rotation: The
-b filesize:{max_file_size_kb}and-b files:{max_rotation_files}parameters tell Tshark to create new PCAP files when the current one hits 500MB, and keep only the last 5 files (overwriting older ones when the limit is reached) — exactly like your originaltcpdump -W 5 -C 500command. - CSV Export: We use
-T fieldsto specify we want structured output, then configure CSV formatting with-Eflags. The-e _ws.col.*fields match the exact columns you listed (No., Time, Source, etc.) as they appear in Wireshark's GUI. - Graceful Shutdown: The
signal_handlerensures we terminate Tshark properly when you press Ctrl+C, preventing corrupted PCAP files. - Interface Selection: Change
capture_interfacefrom "any" to your specific network interface (e.g., "eth0") if you don't want to capture all traffic.
How to Use
- Save the script as
traffic_capture.py - Run it with sudo (required for capture):
sudo python3 traffic_capture.py - To stop the capture, press Ctrl+C
Notes
- If Tshark isn't in your system's PATH, replace
"tshark"in the command with the full path (e.g.,/usr/bin/tsharkon Linux,C:\Program Files\Wireshark\tshark.exeon Windows). - To add traffic filters (like you would with tcpdump), add a
-fparameter to the command, e.g.,"-f", "tcp port 80"to capture only HTTP traffic. - The CSV file will be updated in real-time as packets are captured.
内容的提问来源于stack exchange,提问作者Bat
相关产品推荐
相关产品推荐

