pyshark

repository·master·Indexed 25 days ago

https://github.com/kiminewt/pyshark

A Python wrapper for tshark (the Wireshark command-line utility) that enables packet parsing in Python by leveraging Wireshark's dissectors via XML or JSON export. It provides classes for reading from capture files (FileCapture), live interfaces (LiveCapture, LiveRingCapture), and remote hosts (RemoteCapture). The library supports BPF and Wireshark display filters, automatic decryption for WEP, WPA-PWD, and WPA-PSK, and flexible packet data access via dictionary, attribute, or index styles.

Tokens
6.9K
Snippets
9
Records
46
Agent score
79%

What's inside pyshark

  1. Overview of pyshark

    master
    pyshark is a Python wrapper for tshark (the command-line version of Wireshark). It allows for Python-based packet parsing by leveraging Wireshark's built-in dissectors. This enables developers to analyze network traffic using the same logic and protocol support provided by Wireshark directly within a Python environment.
  2. Install pyshark

    master

    Install the latest version of pyshark from PyPI using pip.

    Requirements:

    • Python 3.7+
    • tshark (Wireshark command-line utility) must be installed on your system.

    Mac OS X Note: You may need to install libxml and Xcode command line tools if you encounter clang or libxml errors:

    xcode-select --install
    pip install libxml
    pip install pyshark
  3. Handle nested fields with EkMultiField

    master

    When a field in an EkLayer contains subfields, get_field() returns an EkMultiField object. You can access subfields in two ways:

    1. Attribute Access: Use __getattr__ to access subfields directly as attributes (e.g., multi_field.subfield_name).
    2. Explicit Method: Use get_field(subfield_name) on the EkMultiField instance.

    You can inspect available subfields using the .subfields property.

  4. How JsonLayer handles 'showname' and 'fake' fields

    master

    The JsonLayer implementation includes logic to handle non-standard JSON structures common in packet dissectors:

    1. Showname Fields: If a JSON key contains a colon (e.g., "Something Special: it's special": { ... }), JsonLayer converts the part before the colon into a normalized field name (lowercase, spaces replaced by underscores). This allows you to access these fields using standard dot notation: pkt.layer.something_special.field.

    2. Fake (Intermediate) Layers: Sometimes the JSON hierarchy is incomplete (e.g., a field foo.bar.baz exists, but there is no explicit bar object). JsonLayer detects these gaps and creates "fake" intermediate layers so that the logical path foo.bar.baz remains traversable.

  5. Access packet data and layers

    master

    Packets are organized into layers. To access data, you must first reach the appropriate layer and then select a field.

    Access Patterns:

    • Dictionary style: packet['ip'].dst
    • Attribute style: packet.ip.src
    • Index style: packet[2].src (accesses the 3rd layer)

    Layer Checks: Check if a layer exists using the in operator:

    'IP' in packet

    Field Discovery: To see all available field names for a layer, use the .field_names attribute:

    packet.ip.field_names

    Field Values:

    • showname: Returns a pretty description of the field.
    • int_value: Returns the integer representation of the field.
    • binary_value: Returns the raw binary data of the field.
  6. Read from a live interface with LiveCapture

    master

    Use pyshark.LiveCapture to sniff packets from a live network interface.

    Common Parameters:

    • interface: Name of the interface (e.g., 'eth0'). If omitted, the first available interface is used.
    • bpf_filter: A BPF (tcpdump) filter to apply.
    • display_filter: A Wireshark display filter to use.
    • output_file: Path to save captured packets to a file.
    • only_summaries: (bool) Produce only packet summaries.
    • decryption_key: Key used for decrypting traffic.
    • encryption_type: Standard of encryption ('WEP', 'WPA-PWD', or 'WPA-PWK').
    • tshark_path: Path to the tshark binary.

    Methods:

    • sniff(timeout=...): Captures packets for a specified duration.
    • sniff_continuously(packet_count=...): A generator that yields packets as they arrive.
    import pyshark
    
    # Sniff for a specific duration
    capture = pyshark.LiveCapture(interface='eth0')
    capture.sniff(timeout=50)
    
    # Continuous sniffing using a generator
    for packet in capture.sniff_continuously(packet_count=5):
        print('Just arrived:', packet)
  7. Read from a remote interface with RemoteCapture

    master

    Use pyshark.RemoteCapture to capture packets from a remote host running rpcapd.

    Common Parameters:

    • remote_host: IP or hostname of the remote machine.
    • remote_interface: The interface name on the remote machine (on Windows, use the true interface name like \Device\NPF_...).
    • remote_port: The port the rpcapd service is listening on.
    • bpf_filter: BPF filter to apply.
    • display_filter: Wireshark display filter to use.
    • only_summaries: (bool) Produce only packet summaries.
    • decryption_key: Key used for decrypting traffic.
    • encryption_type: Standard of encryption ('WEP', 'WPA-PWD', or 'WPA-PWK').
    • tshark_path: Path to the tshark binary.
    import pyshark
    
    capture = pyshark.RemoteCapture('192.168.1.101', 'eth0')
    capture.sniff(timeout=50)
  8. Read from a live interface using a ring buffer with LiveRingCapture

    master

    Use pyshark.LiveRingCapture for live sniffing when you want to use a ring buffer to manage capture files.

    Common Parameters:

    • ring_file_name: Name of the ring file (default: /tmp/pyshark.pcap).
    • ring_file_size: Size of the ring file in kB (default: 1024).
    • num_ring_files: Number of ring files to keep (default: 1).
    • interface: Name of the interface to sniff on.
    • bpf_filter: BPF filter to use.
    • display_filter: Wireshark display filter to use.
    • only_summaries: (bool) Produce only packet summaries.
    • decryption_key: Key used for decrypting traffic.
    • encryption_type: Standard of encryption ('WEP', 'WPA-PWD', or 'WPA-PWK').
    • tshark_path: Path to the tshark binary.
    • output_file: Additionally save captured packets to this file.
    import pyshark
    
    capture = pyshark.LiveRingCapture(interface='eth0')
    capture.sniff(timeout=50)
    for packet in capture.sniff_continuously(packet_count=5):
        print('Just arrived:', packet)
  9. Decrypt packet captures

    master

    Pyshark supports automatic decryption of traces using WEP, WPA-PWD, and WPA-PSK standards.

    Usage: Pass the decryption_key and encryption_type to the capture constructor.

    Supported Encryption Standards: Available via pyshark.FileCapture.SUPPORTED_ENCRYPTION_STANDARDS or pyshark.LiveCapture.SUPPORTED_ENCRYPTION_STANDARDS. Values: ('wep', 'wpa-pwd', 'wpa-psk').

    import pyshark
    
    # Decrypting a file
    cap1 = pyshark.FileCapture('/tmp/capture1.cap', decryption_key='password')
    
    # Decrypting live traffic
    cap2 = pyshark.LiveCapture(interface='wi0', decryption_key='password', encryption_type='wpa-psk')
  10. Read from a capture file with FileCapture

    master

    Use pyshark.FileCapture to parse existing packet capture files (PCAP, PCAP-NG) or TShark XML exports.

    Common Parameters:

    • input_file: Path or file-like object containing the capture.
    • display_filter: A Wireshark display filter to apply before reading.
    • keep_packets: (bool) Whether to keep packets after reading them via next(). Set to False to conserve memory on large files.
    • only_summaries: (bool) Produce only packet summaries (faster, but less data).
    • decryption_key: Key used for decrypting traffic.
    • encryption_type: Standard of encryption ('WEP', 'WPA-PWD', or 'WPA-PWK'). Defaults to 'WPA-PWK'.
    • tshark_path: Path to the tshark binary.
    import pyshark
    cap = pyshark.FileCapture('/tmp/mycapture.cap')
    print(cap[0])
  11. Handle TSharkNotFoundException

    master

    If pyshark cannot locate the TShark binary, it raises TSharkNotFoundException. To resolve this, you should either:

    1. Add the TShark installation directory to your system's PATH environment variable.
    2. Create a config.ini file in your current working directory or the pyshark directory with the following structure:
    [tshark]
    tshark_path = /path/to/your/tshark