PyShark
PyShark is a Python wrapper for TShark, the command-line network protocol analyzer that comes with Wireshark. It allows for Pythonic packet parsing and analysis by leveraging Wireshark's powerful dissection engine. The library is currently at version 0.6 and sees active development with several minor and patch releases per year, addressing compatibility and adding features.
Warnings
- breaking PyShark dropped official support for Python 3.5 and 3.6 starting with version 0.6.
- gotcha PyShark fundamentally relies on `tshark` (the command-line tool for Wireshark) being installed and accessible in your system's PATH. Without `tshark`, PyShark cannot function and will raise a `FileNotFoundError` or similar exception.
- deprecated The older JSON parsing mode is 'likely to be eventually deprecated' in favor of the newer, faster, and easier-to-use EK parsing mode introduced in v0.5.
- gotcha When capturing on Windows, network interface names are typically in the format `\Device\NPF_{GUID}` rather than common names like 'Wi-Fi' or 'Ethernet'. Using the wrong format will result in capture failure.
- gotcha On macOS, `pyshark` might require `libxml` and Xcode command-line developer tools to be installed due to underlying dependencies.
- gotcha There have been reports of parsing errors or incomplete data when using EK mode (`use_ek=True`) in combination with `include_raw=True`, particularly where fields like flags might appear empty.
Install
-
pip install pyshark
Imports
- LiveCapture
from pyshark import LiveCapture
- FileCapture
from pyshark import FileCapture
Quickstart
import pyshark
import os
# Ensure TShark is installed and in your system's PATH.
# For Windows, you might need to specify the interface like r'\Device\NPF_{YOUR-GUID}'
# For macOS, 'en0' or 'en1' are common.
# For Linux, 'eth0' or 'wlan0' are common.
interface_name = os.environ.get('PYSHARK_INTERFACE', 'eth0')
try:
# Create a LiveCapture object to sniff on the specified interface
# Use display_filter for Wireshark-style filtering, e.g., 'http or dns'
capture = pyshark.LiveCapture(interface=interface_name)
print(f"Capturing 5 packets on {interface_name}...")
for packet in capture.sniff_continuously(packet_count=5):
# Access packet layers and fields
protocol = packet.highest_layer
src = packet.ip.src if 'IP' in packet else 'N/A'
dst = packet.ip.dst if 'IP' in packet else 'N/A'
print(f"Packet: {packet.number} | Time: {packet.sniff_time} | Protocol: {protocol} | Source: {src} -> Dest: {dst}")
# Example: print DNS query name if available
if 'DNS' in packet and hasattr(packet.dns, 'qry_name'):
print(f" DNS Query: {packet.dns.qry_name}")
except FileNotFoundError:
print("Error: TShark not found. Please ensure Wireshark/TShark is installed and in your system's PATH.")
except Exception as e:
print(f"An error occurred during capture: {e}")
finally:
if 'capture' in locals() and capture:
capture.close() # Important: ensure the capture process is closed to prevent resource leaks