### Install Pyshark from Git Source: https://github.com/kiminewt/pyshark/blob/master/README.md Clone the pyshark repository and install it from the source. ```bash git clone https://github.com/KimiNewt/pyshark.git cd pyshark/src python setup.py install ``` -------------------------------- ### Install Pyshark using pip Source: https://github.com/kiminewt/pyshark/blob/master/README.md Install the latest version of pyshark from PyPI. ```bash pip install pyshark ``` -------------------------------- ### Install libxml on Mac OS X Source: https://github.com/kiminewt/pyshark/blob/master/README.md Install libxml if you encounter errors during installation on Mac OS X. ```bash xcode-select --install pip install libxml ``` -------------------------------- ### Get Supported Encryption Standards Source: https://context7.com/kiminewt/pyshark/llms.txt Retrieve a tuple of supported encryption standards that can be used for decryption. ```python print(pyshark.FileCapture.SUPPORTED_ENCRYPTION_STANDARDS) # Output: ('wep', 'wpa-pwd', 'wpa-psk') ``` -------------------------------- ### Remote Capture on Windows Interface Source: https://context7.com/kiminewt/pyshark/llms.txt Capture packets from a remote Windows machine using its specific device interface name, typically starting with `\\Device\\NPF_`. ```python capture = pyshark.RemoteCapture( remote_host='192.168.1.50', remote_interface=r'\\Device\\NPF_{GUID-HERE}' ) ``` -------------------------------- ### Layer Field Access with Default Value Source: https://context7.com/kiminewt/pyshark/llms.txt Safely access layer fields using the `get()` method, providing a default value to return if the field does not exist. This prevents `AttributeError` exceptions for missing fields. ```python import pyshark cap = pyshark.FileCapture('/path/to/capture.pcap') packet = cap[0] value = packet.ip.get('nonexistent_field', default='N/A') ``` -------------------------------- ### Ring Capture with All Options Source: https://context7.com/kiminewt/pyshark/llms.txt Demonstrates a ring buffer capture with all available options, including display filter, experimental features (`use_ek`), and decryption parameters. ```python capture = pyshark.LiveRingCapture( interface='eth0', ring_file_size=4096, num_ring_files=3, ring_file_name='/tmp/continuous.pcap', display_filter='http', use_ek=True, decryption_key='wifi_password', encryption_type='wpa-pwd' ) ``` -------------------------------- ### Ring Buffer Capture with Filtering and Timeout Source: https://context7.com/kiminewt/pyshark/llms.txt Configure ring buffer capture with specific file sizes, number of files, file name, BPF filter, display filter, and a capture timeout. ```python capture = pyshark.LiveRingCapture( interface='eth0', ring_file_size=2048, # 2 MB per file num_ring_files=10, # Keep 10 files ring_file_name='/var/log/capture.pcap', bpf_filter='tcp port 443', display_filter='tls' ) capture.sniff(timeout=300) # Capture for 5 minutes ``` -------------------------------- ### Live Capture with Custom Tshark Parameters Source: https://context7.com/kiminewt/pyshark/llms.txt Configure live capture with custom tshark parameters, such as enabling TCP stream deselection. ```python capture = pyshark.LiveCapture( interface='eth0', custom_parameters={'-o': 'tcp.desegment_tcp_streams:TRUE'} ) ``` -------------------------------- ### Basic Ring Buffer Capture Source: https://context7.com/kiminewt/pyshark/llms.txt Capture live network traffic using a ring buffer. Configure file size, number of files, and base file name. ```python capture = pyshark.LiveRingCapture( interface='eth0', ring_file_size=1024, # 1024 KB per file num_ring_files=5, # Keep 5 files (rotate when full) ring_file_name='/tmp/ring_capture.pcap' ) ``` -------------------------------- ### Decrypting Packet Captures with Pyshark Source: https://github.com/kiminewt/pyshark/blob/master/README.md Shows how to initialize captures (file-based and live) with a decryption key and specify the encryption type. Lists supported encryption standards. ```python >>> cap1 = pyshark.FileCapture('/tmp/capture1.cap', decryption_key='password') >>> cap2 = pyshark.LiveCapture(interface='wi0', decryption_key='password', encryption_type='wpa-psk') ``` ```python >>> pyshark.FileCapture.SUPPORTED_ENCRYPTION_STANDARDS ('wep', 'wpa-pwd', 'wpa-psk') ``` ```python >>> pyshark.LiveCapture.SUPPORTED_ENCRYPTION_STANDARDS ('wep', 'wpa-pwd', 'wpa-psk') ``` -------------------------------- ### Live Capture with Debug Mode Source: https://context7.com/kiminewt/pyshark/llms.txt Enable debug mode for troubleshooting live captures. Use `set_debug()` to activate debug logging. ```python capture = pyshark.LiveCapture(interface='eth0', debug=True) capture.set_debug() ``` -------------------------------- ### Live Capture with File Output Source: https://context7.com/kiminewt/pyshark/llms.txt Capture live network traffic and save it to a pcap file simultaneously. Specify the interface and output file path. ```python capture = pyshark.LiveCapture( interface='eth0', output_file='/tmp/live_capture.pcap' ) capture.sniff(timeout=60) ``` -------------------------------- ### Live Capture Options Source: https://github.com/kiminewt/pyshark/blob/master/README.md Options available when performing a live packet capture. ```APIDOC ## Live Capture Options ### Description These are the available options for configuring a live packet capture using Pyshark. ### Parameters #### Query Parameters - **param ring_file_size** (integer) - Optional - Size of the ring file in kB, default is 1024 - **param num_ring_files** (integer) - Optional - Number of ring files to keep, default is 1 - **param ring_file_name** (string) - Optional - Name of the ring file, default is /tmp/pyshark.pcap - **param interface** (string) - Optional - Name of the interface to sniff on. If not given, takes the first available. - **param bpf_filter** (string) - Optional - BPF filter to use on packets. - **param display_filter** (string) - Optional - Display (wireshark) filter to use. - **param only_summaries** (boolean) - Optional - Only produce packet summaries, much faster but includes very little information - **param disable_protocol** (string) - Optional - Disable detection of a protocol (tshark > version 2) - **param decryption_key** (string) - Optional - Key used to encrypt and decrypt captured traffic. - **param encryption_type** (string) - Optional - Standard of encryption used in captured traffic (must be either 'WEP', 'WPA-PWD', or 'WPA-PWK'. Defaults to WPA-PWK). - **param tshark_path** (string) - Optional - Path of the tshark binary - **param output_file** (string) - Optional - Additionally save captured packets to this file. ``` -------------------------------- ### Accessing Packet Data in Pyshark Source: https://github.com/kiminewt/pyshark/blob/master/README.md Demonstrates various methods to access packet layers and fields, including dictionary-like access, attribute access, and index-based access. Also shows how to check for layer existence and retrieve field details. ```python >>> packet['ip'].dst 192.168.0.1 ``` ```python >>> packet.ip.src 192.168.0.100 ``` ```python >>> packet[2].src 192.168.0.100 ``` ```python >>> 'IP' in packet True ``` ```python >>> p.ip.addr.showname Source or Destination Address: 10.0.0.10 (10.0.0.10) ``` ```python >>> p.ip.addr.int_value 167772170 ``` ```python >>> p.ip.addr.binary_value b'\n\x00\x00\n' ``` -------------------------------- ### In-Memory Capture with Different Link Types Source: https://context7.com/kiminewt/pyshark/llms.txt Initialize an in-memory capture with a specific link layer type, such as Ethernet (default) or IEEE 802.11 (WiFi). ```python import pyshark from pyshark.capture.inmem_capture import LinkTypes capture = pyshark.InMemCapture(linktype=LinkTypes.ETHERNET) # Default # capture = pyshark.InMemCapture(linktype=LinkTypes.IEEE802_11) # WiFi ``` -------------------------------- ### LiveCapture - Capture Live Network Traffic Source: https://context7.com/kiminewt/pyshark/llms.txt Use LiveCapture to sniff network traffic in real-time from a specified interface. Supports BPF filters for kernel-level filtering and display filters for Wireshark-style filtering. Can capture on multiple interfaces or all available interfaces. Monitor mode is available for WiFi capture. `sniff()` captures packets and stores them in the object, while `sniff_continuously()` provides a generator for real-time processing. ```python import pyshark # Basic live capture on specific interface capture = pyshark.LiveCapture(interface='eth0') # Sniff with timeout (capture for 30 seconds) capture.sniff(timeout=30) print(f"Captured {len(capture)} packets") # Access captured packets for packet in capture: print(packet) # Sniff specific number of packets capture = pyshark.LiveCapture(interface='eth0') capture.sniff(packet_count=100) # Continuous sniffing with generator (real-time processing) capture = pyshark.LiveCapture(interface='eth0') for packet in capture.sniff_continuously(packet_count=50): print(f'Received: {packet.highest_layer} packet') if 'IP' in packet: print(f' {packet.ip.src} -> {packet.ip.dst}') # Using BPF filter (kernel-level filtering, more efficient) capture = pyshark.LiveCapture( interface='eth0', bpf_filter='tcp port 80' ) # Using display filter (Wireshark filter syntax) capture = pyshark.LiveCapture( interface='eth0', display_filter='http.request.method == "GET"' ) # Capture on multiple interfaces multi_cap = pyshark.LiveCapture(interface=['eth0', 'eth1']) # Capture on all available interfaces all_cap = pyshark.LiveCapture() # interface=None captures all # Monitor mode for WiFi capture wifi_cap = pyshark.LiveCapture( interface='wlan0', monitor_mode=True ) ``` -------------------------------- ### Use Only Summaries Mode Source: https://context7.com/kiminewt/pyshark/llms.txt Enable `only_summaries=True` for significantly faster packet processing with less detail. This mode is useful when only packet summaries are needed, not full layer details. ```python capture = pyshark.FileCapture( '/path/to/capture.pcap', only_summaries=True ) for pkt in capture: print(pkt) # Summary only, no layer details ``` -------------------------------- ### Live Capture with Packet Callback Source: https://context7.com/kiminewt/pyshark/llms.txt Apply a function to each captured packet. The callback can process packet data, including checking for specific layers like HTTP. ```python def process_packet(packet): print(f"Packet: {packet}") if hasattr(packet, 'http'): print(f"HTTP Host: {packet.http.host}") capture = pyshark.LiveCapture(interface='eth0') capture.apply_on_packets(process_packet, timeout=30) ``` -------------------------------- ### PipeCapture with Filters and Callbacks Source: https://context7.com/kiminewt/pyshark/llms.txt Configure `PipeCapture` with display filters and use `apply_on_packets` to process packets with a callback function. The pipe is closed automatically when `close()` is called. ```python import pyshark import os read_fd, write_fd = os.pipe() capture = pyshark.PipeCapture( pipe=read_fd, display_filter='http', use_ek=True ) def handle_packet(pkt): print(f"Received: {pkt.highest_layer}") capture.apply_on_packets(handle_packet) capture.close() ``` -------------------------------- ### Pretty Printing and Showing Packet/Layer Data Source: https://context7.com/kiminewt/pyshark/llms.txt Use `pretty_print()` or `show()` methods on a packet object for a human-readable, hierarchical display of all layers and fields. A specific layer can also be printed directly. ```python import pyshark cap = pyshark.FileCapture('/path/to/capture.pcap') packet = cap[0] # Pretty print packet packet.pretty_print() # Or equivalently: packet.show() # Print specific layer print(packet.ip) ``` -------------------------------- ### Capture Live Remote Traffic with Pyshark Source: https://github.com/kiminewt/pyshark/blob/master/README.md Initiates a remote capture from a specified host and interface. The capture runs for a defined timeout period. Ensure rpcapd is running on the remote host. ```python >>> capture = pyshark.RemoteCapture('192.168.1.101', 'eth0') >>> capture.sniff(timeout=50) >>> capture ``` -------------------------------- ### Read packets from a live interface Source: https://github.com/kiminewt/pyshark/blob/master/README.md Capture packets from a live network interface (e.g., 'eth0') for a specified duration. Packets can be accessed by index or iterated over. ```python capture = pyshark.LiveCapture(interface='eth0') capture.sniff(timeout=50) capture capture[3] for packet in capture.sniff_continuously(packet_count=5): print('Just arrived:', packet) ``` -------------------------------- ### FileCapture - Read Packets from Capture Files Source: https://context7.com/kiminewt/pyshark/llms.txt Use FileCapture to read packets from PCAP or PCAPNG files. Supports display filters, decryption, custom protocols, and memory-efficient streaming for large files. Use `keep_packets=False` for memory efficiency. `use_ek=True` enables faster parsing. Decryption requires `decryption_key` and `encryption_type`. Custom protocols are set with `decode_as`. Filtered packets can be saved to a new file using `output_file`. The context manager ensures automatic cleanup. ```python import pyshark # Basic file capture - reads all packets cap = pyshark.FileCapture('/path/to/capture.pcap') # Iterate through packets for packet in cap: print(f"Packet #{packet.number}: {packet.highest_layer}") print(f" Length: {packet.length} bytes") print(f" Time: {packet.sniff_time}") # Access layers by name or index if 'IP' in packet: print(f" Source IP: {packet.ip.src}") print(f" Dest IP: {packet.ip.dst}") if 'TCP' in packet: print(f" Source Port: {packet.tcp.srcport}") print(f" Dest Port: {packet.tcp.dstport}") # Access packets by index print(cap[0]) # First packet print(cap[5]) # Sixth packet # File capture with display filter (only DNS traffic) dns_cap = pyshark.FileCapture( '/path/to/capture.pcap', display_filter='dns' ) for pkt in dns_cap: print(f"DNS Query: {pkt.dns.qry_name}") # Memory-efficient capture for large files (don't keep packets in memory) large_cap = pyshark.FileCapture( '/path/to/large_capture.pcap', keep_packets=False ) for pkt in large_cap: process_packet(pkt) # Packet not retained after iteration # Using EK JSON mode for faster parsing fast_cap = pyshark.FileCapture( '/path/to/capture.pcap', use_ek=True ) # Decrypt encrypted WiFi traffic encrypted_cap = pyshark.FileCapture( '/path/to/wifi_capture.pcap', decryption_key='mypassword', encryption_type='wpa-pwd' ) # Custom protocol decoding custom_cap = pyshark.FileCapture( '/path/to/capture.pcap', decode_as={'tcp.port==8080': 'http'} ) # Save filtered packets to new file filtered_cap = pyshark.FileCapture( '/path/to/capture.pcap', display_filter='http', output_file='/path/to/filtered.pcap' ) # Context manager for automatic cleanup with pyshark.FileCapture('/path/to/capture.pcap') as cap: for packet in cap: print(packet) # Capture automatically closed ``` -------------------------------- ### Accessing Specific Protocol Fields (TCP, HTTP, DNS) Source: https://context7.com/kiminewt/pyshark/llms.txt Access fields specific to common protocols like TCP, HTTP, and DNS. Check for layer existence before accessing its fields to avoid errors. ```python import pyshark cap = pyshark.FileCapture('/path/to/capture.pcap') packet = cap[0] # TCP layer examples if 'TCP' in packet: print(f"Src Port: {packet.tcp.srcport}") print(f"Dst Port: {packet.tcp.dstport}") print(f"Flags: {packet.tcp.flags}") print(f"Sequence: {packet.tcp.seq}") print(f"Ack: {packet.tcp.ack}") # HTTP layer examples if 'HTTP' in packet: print(f"Host: {packet.http.host}") print(f"Method: {packet.http.request_method}") print(f"URI: {packet.http.request_uri}") # DNS layer examples if 'DNS' in packet: print(f"Query: {packet.dns.qry_name}") print(f"Type: {packet.dns.qry_type}") ``` -------------------------------- ### Configure TShark Path and Preferences Source: https://context7.com/kiminewt/pyshark/llms.txt Customize TShark's behavior by setting the tshark path, overriding preferences, disabling specific dissectors, or passing custom parameters directly to TShark. ```python capture = pyshark.FileCapture( '/path/to/capture.pcap', tshark_path='/usr/local/bin/tshark' ) ``` ```python capture = pyshark.FileCapture( '/path/to/capture.pcap', override_prefs={ 'tcp.desegment_tcp_streams': 'TRUE', 'http.desegment_body': 'TRUE', 'ssl.keys_list': '/path/to/keyfile' } ) ``` ```python capture = pyshark.FileCapture( '/path/to/capture.pcap', disable_protocol='http' ) ``` ```python capture = pyshark.FileCapture( '/path/to/capture.pcap', custom_parameters={'--disable-heuristic': 'some_heuristic'} ) ``` ```python # Or as a list capture = pyshark.FileCapture( '/path/to/capture.pcap', custom_parameters=['-o', 'gui.column.format:"Time","%t"'] ) ``` -------------------------------- ### Basic Remote Capture Source: https://context7.com/kiminewt/pyshark/llms.txt Capture packets from a remote machine using the rpcapd service. Specify the remote host and interface. ```python capture = pyshark.RemoteCapture( remote_host='192.168.1.100', remote_interface='eth0' ) capture.sniff(timeout=30) ``` -------------------------------- ### Remote Live Capture Source: https://github.com/kiminewt/pyshark/blob/master/README.md Capturing packets from a live remote interface. ```APIDOC ## Reading from a live remote interface ### Description This section describes how to capture packets from a live remote interface using Pyshark. ### Method `pyshark.RemoteCapture` ### Endpoint N/A (Remote connection) ### Parameters #### Query Parameters - **param remote_host** (string) - Required - The remote host to capture on (IP or hostname). Should be running rpcapd. - **param remote_interface** (string) - Required - The remote interface on the remote machine to capture on. Note that on windows it is not the device display name but the true interface name (i.e. \Device\NPF_..). - **param remote_port** (integer) - Optional - The remote port the rpcapd service is listening on - **param bpf_filter** (string) - Optional - A BPF (tcpdump) filter to apply on the cap before reading. - **param only_summaries** (boolean) - Optional - Only produce packet summaries, much faster but includes very little information - **param disable_protocol** (string) - Optional - Disable detection of a protocol (tshark > version 2) - **param decryption_key** (string) - Optional - Key used to encrypt and decrypt captured traffic. - **param encryption_type** (string) - Optional - Standard of encryption used in captured traffic (must be either 'WEP', 'WPA-PWD', or 'WPA-PWK'. Defaults to WPA-PWK). - **param tshark_path** (string) - Optional - Path of the tshark binary ### Request Example ```python >>> capture = pyshark.RemoteCapture('192.168.1.101', 'eth0') >>> capture.sniff(timeout=50) >>> capture ``` ``` -------------------------------- ### Read from File with Display Filter in Pyshark Source: https://github.com/kiminewt/pyshark/blob/master/README.md Captures packets from a file using a Wireshark display filter. This allows for more flexible filtering compared to BPF filters. ```python >>> cap1 = pyshark.FileCapture('/tmp/capture1.cap', display_filter="dns") >>> cap2 = pyshark.LiveCapture(interface='en0', display_filter="tcp.analysis.retransmission") ``` -------------------------------- ### Remote Capture with BPF Filter Source: https://context7.com/kiminewt/pyshark/llms.txt Apply a Berkeley Packet Filter (BPF) to limit the packets captured from a remote machine. ```python capture = pyshark.RemoteCapture( remote_host='192.168.1.100', remote_interface='eth0', bpf_filter='tcp port 80 or tcp port 443' ) ``` -------------------------------- ### File Capture with Display Filter Source: https://github.com/kiminewt/pyshark/blob/master/README.md Using display filters when reading packet captures from a file. ```APIDOC ## Reading from a file using a display filter ### Description This section explains how to use Pyshark's display filters when reading packet captures from a file. Display filters offer more flexibility than BPF filters for analyzing specific traffic. ### Usage Specify the `display_filter` parameter when creating a `FileCapture` or `LiveCapture` object. ```python >>> cap1 = pyshark.FileCapture('/tmp/capture1.cap', display_filter="dns") >>> cap2 = pyshark.LiveCapture(interface='en0', display_filter="tcp.analysis.retransmission") ``` ``` -------------------------------- ### Read packets from a live interface using a ring buffer Source: https://github.com/kiminewt/pyshark/blob/master/README.md Capture packets from a live network interface using a ring buffer for efficient memory management. Packets can be accessed by index or iterated over. ```python capture = pyshark.LiveRingCapture(interface='eth0') capture.sniff(timeout=50) capture capture[3] for packet in capture.sniff_continuously(packet_count=5): print('Just arrived:', packet) ``` -------------------------------- ### Parse In-Memory Packets with Display Filter Source: https://context7.com/kiminewt/pyshark/llms.txt Apply a display filter when parsing raw packets in memory to process only packets matching the filter criteria. ```python import pyshark capture = pyshark.InMemCapture(display_filter='ip') parsed = capture.parse_packets(packets) capture.close() ``` -------------------------------- ### Field Value Representations Source: https://context7.com/kiminewt/pyshark/llms.txt Fields can be represented in various formats: default string, display name, raw hex, integer, binary bytes, and hex integer. `showname_key` and `showname_value` provide labeled representations. ```python import pyshark cap = pyshark.FileCapture('/path/to/capture.pcap') packet = cap[0] field = packet.ip.addr print(field) # Default string value print(field.showname) # Pretty display: "Source or Destination Address: 10.0.0.10" print(field.raw_value) # Raw hex value print(field.int_value) # Integer value: 167772170 print(field.binary_value) # Binary bytes: b'\n\x00\x00\n' print(field.hex_value) # Hex as int (for hex-formatted values) print(field.showname_key) # Field label print(field.showname_value) # Field display value ``` -------------------------------- ### Read packets from a capture file Source: https://github.com/kiminewt/pyshark/blob/master/README.md Load and parse packets from a PCAP file using FileCapture. The first packet is printed showing its layers and fields. ```python import pyshark cap = pyshark.FileCapture('/tmp/mycapture.cap') cap print cap[0] ``` -------------------------------- ### Remote Capture with Custom Port Source: https://context7.com/kiminewt/pyshark/llms.txt Perform remote capture specifying a custom port for the rpcapd service if it's not using the default (2002). ```python capture = pyshark.RemoteCapture( remote_host='10.0.0.50', remote_interface='eth0', remote_port=2002 # Default rpcapd port ) ``` -------------------------------- ### Parse Multiple Raw Packets In-Memory Source: https://context7.com/kiminewt/pyshark/llms.txt Parse multiple raw binary packets efficiently in memory. This method is more performant than parsing packets individually. ```python import pyshark capture = pyshark.InMemCapture() packets = [raw_packet1, raw_packet2, raw_packet3] parsed_packets = capture.parse_packets(packets) for pkt in parsed_packets: print(pkt) capture.close() ``` -------------------------------- ### In-Memory Packet Capture Source: https://context7.com/kiminewt/pyshark/llms.txt Use `InMemCapture` to add packets to an internal list for later processing. This is useful for collecting a set of packets without writing to a file. ```python import pyshark capture = pyshark.InMemCapture() parsed = capture.feed_packets([raw_packet1, raw_packet2]) print(f"Total packets: {len(capture)}") for pkt in capture: print(pkt) ``` -------------------------------- ### Process Each Packet with a Callback Source: https://context7.com/kiminewt/pyshark/llms.txt Use `apply_on_packets` to process each captured packet with a specified callback function. This can be limited by timeout or packet count. Supports asynchronous callbacks and stopping the capture from within a callback. ```python import pyshark capture = pyshark.LiveCapture(interface='eth0') def packet_callback(packet): """Called for each packet""" print(f"Packet: {packet.highest_layer}") if 'HTTP' in packet: print(f" HTTP Request to: {packet.http.host}") # Process packets for 60 seconds capture.apply_on_packets(packet_callback, timeout=60) # Process specific number of packets capture.apply_on_packets(packet_callback, packet_count=100) ``` ```python async def async_callback(packet): print(f"Async processing: {packet}") await some_async_operation(packet) capture.apply_on_packets(async_callback, timeout=30) ``` ```python from pyshark.capture.capture import StopCapture def selective_callback(packet): if 'HTTP' in packet and 'login' in str(packet): print("Found login request, stopping") raise StopCapture() print(packet) capture.apply_on_packets(selective_callback) ``` -------------------------------- ### Load Packets into Internal List Source: https://context7.com/kiminewt/pyshark/llms.txt Use `load_packets` to load a specified number of packets or load for a duration into an internal list. This allows for batch processing and analysis of captured data. The capture can be cleared or reset. ```python capture = pyshark.LiveCapture(interface='eth0') capture.load_packets(packet_count=50) # Load 50 packets print(f"Loaded {len(capture)} packets") # Access loaded packets for packet in capture: print(packet) ``` ```python # Load with timeout capture.load_packets(timeout=30) # Load for 30 seconds ``` ```python # Combine count and timeout capture.load_packets(packet_count=1000, timeout=60) # Whichever comes first ``` ```python # Clear and reset capture.clear() # Remove all packets capture.reset() # Reset iterator to beginning ``` -------------------------------- ### Retrieving Raw Packet Bytes Source: https://context7.com/kiminewt/pyshark/llms.txt Obtain the raw byte data of a packet by setting `use_json=True` and `include_raw=True` during `FileCapture` initialization. Use `get_raw_packet()` to access the bytes, which can then be converted to hex. ```python import pyshark cap = pyshark.FileCapture('/path/to/capture.pcap', use_json=True, include_raw=True) packet = cap[0] raw_bytes = packet.get_raw_packet() print(f"Raw bytes: {raw_bytes.hex()}") ``` -------------------------------- ### Accessing Packet Data Source: https://github.com/kiminewt/pyshark/blob/master/README.md How to access and interpret packet data within Pyshark. ```APIDOC ## Accessing packet data ### Description Packets in Pyshark are structured by layers, and data can be accessed through these layers and their fields. ### Usage Data can be accessed in multiple ways: ```python >>> packet['ip'].dst 192.168.0.1 >>> packet.ip.src 192.168.0.100 >>> packet[2].src 192.168.0.100 ``` To check if a layer exists in a packet: ```python >>> 'IP' in packet True ``` To view all available field names for a layer, use `packet.layer.field_names`: ```python >>> packet.ip.field_names ``` To get the original binary data or a pretty description of a field: ```python >>> p.ip.addr.showname Source or Destination Address: 10.0.0.10 (10.0.0.10) >>> p.ip.addr.int_value 167772170 >>> p.ip.addr.binary_value b'\n\x00\x00\n' ``` ``` -------------------------------- ### Handling Multiple Layers of the Same Type Source: https://context7.com/kiminewt/pyshark/llms.txt Use `get_multiple_layers` to retrieve all instances of a specific layer type, such as multiple VLAN tags in a packet. Iterate through the returned list to access each layer's properties. ```python import pyshark cap = pyshark.FileCapture('/path/to/capture.pcap') packet = cap[0] # Get multiple layers of same type (e.g., double VLAN) vlan_layers = packet.get_multiple_layers('vlan') for vlan in vlan_layers: print(f"VLAN ID: {vlan.id}") ``` -------------------------------- ### Accessing Packet Layers by Name and Index Source: https://context7.com/kiminewt/pyshark/llms.txt Layers can be accessed directly by their name (e.g., `packet.ip` or `packet['ip']`) or by their numerical index. The `layers` attribute provides an iterable of all layers in the packet. ```python import pyshark cap = pyshark.FileCapture('/path/to/capture.pcap') packet = cap[0] # Access layers by name (case-insensitive) ip_layer = packet['ip'] ip_layer = packet.ip # Alternative syntax # Access layers by index first_layer = packet[0] # Usually Ethernet second_layer = packet[1] # Usually IP # List all layers for layer in packet.layers: print(f"Layer: {layer.layer_name}") ``` -------------------------------- ### Iterate Through Remote Packets Source: https://context7.com/kiminewt/pyshark/llms.txt Continuously capture packets from a remote machine and iterate through them, processing a specified number of packets. ```python for packet in capture.sniff_continuously(packet_count=100): print(f"Remote packet: {packet}") ``` -------------------------------- ### Remote Capture with Decryption Source: https://context7.com/kiminewt/pyshark/llms.txt Perform remote capture and decrypt traffic using provided decryption key and encryption type, such as WPA-PSK. ```python capture = pyshark.RemoteCapture( remote_host='192.168.1.100', remote_interface='wlan0', decryption_key='secret_key', encryption_type='wpa-pwd' ) ``` -------------------------------- ### Enable Debug Mode Source: https://context7.com/kiminewt/pyshark/llms.txt Debug mode can be enabled during capture creation or after. It allows for detailed logging of TShark's activity. Debugging can be disabled, and custom log levels can be set. ```python import pyshark import logging # Enable debug mode at capture creation capture = pyshark.FileCapture('/path/to/capture.pcap', debug=True) ``` ```python # Enable debug mode after creation capture = pyshark.LiveCapture(interface='eth0') capture.set_debug() # Enable with default log level capture.set_debug(set_to=True, log_level=logging.DEBUG) ``` ```python # Disable debug mode capture.set_debug(set_to=False) ``` -------------------------------- ### Parse In-Memory Packets with Sniff Times Source: https://context7.com/kiminewt/pyshark/llms.txt Parse multiple raw packets in memory while providing custom sniff times for each packet, useful for replaying or analyzing packet timing. ```python import pyshark import datetime capture = pyshark.InMemCapture() packets = [raw_packet1, raw_packet2] times = [datetime.datetime.now(), datetime.datetime.now()] parsed = capture.parse_packets(packets, sniff_times=times) capture.close() ``` -------------------------------- ### Parse Single Raw Packet In-Memory Source: https://context7.com/kiminewt/pyshark/llms.txt Parse a single raw binary packet in memory without needing a capture file or live interface. Ensure to close the capture manually. ```python import pyshark from pyshark.capture.inmem_capture import LinkTypes capture = pyshark.InMemCapture() # Example: Raw ethernet frame bytes raw_packet = bytes([ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, # Dest MAC 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, # Src MAC 0x08, 0x00, # EtherType (IPv4) # ... IP header and payload ]) parsed = capture.parse_packet(raw_packet) print(f"Parsed: {parsed}") capture.close() # Must close manually ``` -------------------------------- ### Accessing Layer Field Names and Values Source: https://context7.com/kiminewt/pyshark/llms.txt Retrieve all field names within a layer using `field_names`. Individual field values can be accessed using dot notation (e.g., `packet.ip.src`). ```python import pyshark cap = pyshark.FileCapture('/path/to/capture.pcap') packet = cap[0] # Get all field names in a layer print(packet.ip.field_names) # Output: ['version', 'hdr_len', 'dsfield', 'len', 'id', 'flags', 'ttl', 'proto', 'checksum', 'src', 'dst', ...] # Access field values print(packet.ip.src) # Source IP as string: '192.168.1.1' print(packet.ip.dst) # Destination IP print(packet.ip.ttl) # Time to live print(packet.ip.proto) # Protocol number ``` -------------------------------- ### Decrypting Packet Captures Source: https://github.com/kiminewt/pyshark/blob/master/README.md Information on how to decrypt captured traffic using Pyshark. ```APIDOC ## Decrypting packet captures ### Description Pyshark supports automatic decryption of traces using WEP, WPA-PWD, and WPA-PSK standards. ### Usage Provide the `decryption_key` and optionally `encryption_type` when creating a capture object. ```python >>> cap1 = pyshark.FileCapture('/tmp/capture1.cap', decryption_key='password') >>> cap2 = pyshark.LiveCapture(interface='wi0', decryption_key='password', encryption_type='wpa-psk') ``` ### Supported Encryption Standards A tuple of supported encryption standards, `SUPPORTED_ENCRYPTION_STANDARDS`, is available in each capture class. ```python >>> pyshark.FileCapture.SUPPORTED_ENCRYPTION_STANDARDS ('wep', 'wpa-pwd', 'wpa-psk') >>> pyshark.LiveCapture.SUPPORTED_ENCRYPTION_STANDARDS ('wep', 'wpa-pwd', 'wpa-psk') ``` ``` -------------------------------- ### Accessing Basic Packet Properties Source: https://context7.com/kiminewt/pyshark/llms.txt Retrieve fundamental packet attributes like number, length, capture time, and the highest layer protocol. Layers can be checked for existence using the 'in' operator. ```python import pyshark cap = pyshark.FileCapture('/path/to/capture.pcap') packet = cap[0] # Basic packet properties print(f"Packet number: {packet.number}") print(f"Packet length: {packet.length}") print(f"Captured length: {packet.captured_length}") print(f"Sniff time: {packet.sniff_time}") # datetime object print(f"Highest layer: {packet.highest_layer}") print(f"Transport layer: {packet.transport_layer}") # Check if layer exists if 'IP' in packet: print("Packet contains IP layer") if 'TCP' in packet: print("Packet contains TCP layer") ``` -------------------------------- ### Reading Packets from a Pipe Source: https://context7.com/kiminewt/pyshark/llms.txt Utilize `PipeCapture` to read pcap data from a file descriptor or pipe. This is ideal for streaming packet data from external processes. ```python import pyshark import os # Create a pipe and capture from it read_fd, write_fd = os.pipe() # In another thread/process, write pcap data to write_fd # ... # Create pipe capture from read end capture = pyshark.PipeCapture(pipe=read_fd) # Iterate through packets for packet in capture.sniff_continuously(): print(f"Packet from pipe: {packet}") ``` -------------------------------- ### Continuous Ring Buffer Capture Source: https://context7.com/kiminewt/pyshark/llms.txt Continuously capture packets using a ring buffer and iterate through them as they arrive. Access packet layers like `highest_layer`. ```python for packet in capture.sniff_continuously(): print(f'Packet: {packet.highest_layer}') ``` -------------------------------- ### Asynchronous Packet Parsing Source: https://context7.com/kiminewt/pyshark/llms.txt Parse packets asynchronously using `parse_packets_async` for non-blocking operations. Ensure to close the capture asynchronously afterwards. ```python import asyncio import pyshark async def parse_async(): capture = pyshark.InMemCapture() packets = [raw_packet1, raw_packet2] parsed = await capture.parse_packets_async(packets) await capture.close_async() return parsed results = asyncio.run(parse_async()) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.