PyShark

0.6 · active · verified Sun Apr 12

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

Install

Imports

Quickstart

This quickstart demonstrates how to perform a live packet capture using `pyshark.LiveCapture`. It sniffs 5 packets on a specified network interface (defaulting to 'eth0' or an environment variable) and prints basic information about each packet. It also includes error handling for the common `TShark not found` issue and ensures the capture process is properly closed. Remember to replace 'eth0' with your actual network interface name or set the `PYSHARK_INTERFACE` environment variable.

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

view raw JSON →