Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_capture_gets_decoding_parameters():
c = Capture(decode_as={'tcp.port==8888': 'http'})
params = c.get_parameters()
decode_index = params.index('-d')
assert params[decode_index + 1] == 'tcp.port==8888,http'
def test_capture_gets_multiple_decoding_parameters():
c = Capture(decode_as={'tcp.port==8888': 'http', 'tcp.port==6666': 'dns'})
params = c.get_parameters()
decode_index = params.index('-d')
possible_results = ['tcp.port==8888,http', 'tcp.port==6666,dns']
assert params[decode_index + 1] in possible_results
possible_results.remove(params[decode_index + 1])
decode_index = params.index('-d', decode_index + 1)
assert params[decode_index + 1] == possible_results[0]
import os
import sys
from pyshark.capture.capture import Capture
# Define basestring as str if we're in python3.
if sys.version_info >= (3, 0):
basestring = str
class FileCapture(Capture):
"""
A class representing a capture read from a file.
"""
def __init__(self, input_file=None, keep_packets=True, display_filter=None, only_summaries=False,
decryption_key=None, encryption_type='wpa-pwk'):
"""
Creates a packet capture object by reading from file.
:param keep_packets: Whether to keep packets after reading them via next(). Used to conserve memory when reading
large caps (can only be used along with the "lazy" option!)
:param input_file: File path of the capture (PCAP, PCAPNG)
:param bpf_filter: A BPF (tcpdump) filter to apply on the cap before reading.
:param display_filter: A display (wireshark) filter to apply on the cap before reading it.
:param only_summaries: Only produce packet summaries, much faster but includes very little information.
:param decryption_key: Optional key used to encrypt and decrypt captured traffic.
from pyshark.capture.capture import Capture
class PipeCapture(Capture):
def __init__(self, pipe, display_filter=None, only_summaries=False,
decryption_key=None, encryption_type='wpa-pwk', decode_as=None,
disable_protocol=None, tshark_path=None, override_prefs=None, use_json=False, include_raw=False,
eventloop=None, custom_parameters=None, debug=False):
"""
Receives a file-like and reads the packets from there (pcap format).
:param bpf_filter: BPF filter to use on packets.
:param display_filter: Display (wireshark) filter to use.
:param only_summaries: Only produce packet summaries, much faster but includes very little information
:param decryption_key: Key used to encrypt and decrypt captured traffic.
:param encryption_type: Standard of encryption used in captured traffic (must be either 'WEP', 'WPA-PWD',
or 'WPA-PWK'. Defaults to WPA-PWK).
:param decode_as: A dictionary of {decode_criterion_string: decode_as_protocol} that are used to tell tshark
to decode protocols in situations it wouldn't usually, for instance {'tcp.port==8888': 'http'} would make
it attempt to decode any port 8888 traffic as HTTP. See tshark documentation for details.
import os
from pyshark.capture.capture import Capture
class FileCapture(Capture):
"""A class representing a capture read from a file."""
def __init__(self, input_file=None, keep_packets=True, display_filter=None, only_summaries=False,
decryption_key=None, encryption_type="wpa-pwk", decode_as=None,
disable_protocol=None, tshark_path=None, override_prefs=None,
use_json=False, output_file=None, include_raw=False, eventloop=None, custom_parameters=None,
debug=False):
"""Creates a packet capture object by reading from file.
:param keep_packets: Whether to keep packets after reading them via next(). Used to conserve memory when reading
large caps (can only be used along with the "lazy" option!)
:param input_file: File path of the capture (PCAP, PCAPNG)
:param display_filter: A display (wireshark) filter to apply on the cap before reading it.
:param only_summaries: Only produce packet summaries, much faster but includes very little information.
:param decryption_key: Optional key used to encrypt and decrypt captured traffic.
:param encryption_type: Standard of encryption used in captured traffic (must be either 'WEP', 'WPA-PWD', or
async def _get_tshark_process(self, packet_count=None, stdin=None):
read, write = os.pipe()
dumpcap_params = [get_process_path(process_name="dumpcap", tshark_path=self.tshark_path)] + self._get_dumpcap_parameters()
self._log.debug("Creating Dumpcap subprocess with parameters: %s" % " ".join(dumpcap_params))
dumpcap_process = await asyncio.create_subprocess_exec(*dumpcap_params, stdout=write,
stderr=self._stderr_output())
self._created_new_process(dumpcap_params, dumpcap_process, process_name="Dumpcap")
tshark = await super(LiveCapture, self)._get_tshark_process(packet_count=packet_count, stdin=read)
return tshark
# Backwards compatibility
sniff = Capture.load_packets
def sniff_continuously(self, packet_count=None):
"""Captures from the set interface, returning a generator which returns packets continuously.
Can be used as follows:
for packet in capture.sniff_continuously():
print('Woo, another packet:', packet)
Note: you can also call capture.apply_on_packets(packet_callback) which should have a slight performance boost.
:param packet_count: an amount of packets to capture, then stop.
"""
# Retained for backwards compatibility and to add documentation.
return self._packets_from_tshark_sync(packet_count=packet_count)
import os
import asyncio
import sys
from distutils.version import LooseVersion
from pyshark.capture.capture import Capture
from pyshark.tshark.tshark import get_tshark_interfaces, get_process_path
class LiveCapture(Capture):
"""Represents a live capture on a network interface."""
def __init__(self, interface=None, bpf_filter=None, display_filter=None, only_summaries=False,
decryption_key=None, encryption_type='wpa-pwk', output_file=None, decode_as=None,
disable_protocol=None, tshark_path=None, override_prefs=None, capture_filter=None,
monitor_mode=False, use_json=False, include_raw=False, eventloop=None, custom_parameters=None,
debug=False):
"""Creates a new live capturer on a given interface. Does not start the actual capture itself.
:param interface: Name of the interface to sniff on or a list of names (str). If not given, runs on all interfaces.
:param bpf_filter: BPF filter to use on packets.
:param display_filter: Display (wireshark) filter to use.
:param only_summaries: Only produce packet summaries, much faster but includes very little information
:param decryption_key: Optional key used to encrypt and decrypt captured traffic.
:param encryption_type: Standard of encryption used in captured traffic (must be either 'WEP', 'WPA-PWD', or
'WPA-PWK'. Defaults to WPA-PWK).
import trollius as asyncio
from trollius import subprocess, From, Return
from pyshark.capture.capture import Capture
class LinkTypes(object):
NULL = 0
ETHERNET = 1
IEEE802_5 = 6
PPP = 9
IEEE802_11 = 105
class InMemCapture(Capture):
def __init__(self, bpf_filter=None, display_filter=None, only_summaries=False,
decryption_key=None, encryption_type='wpa-pwk'):
"""
Creates a new in-mem capture, a capture capable of receiving binary packets and parsing them using tshark.
Currently opens a new instance of tshark for every packet buffer,
so it is very slow -- try inserting more than one packet at a time if possible.
:param bpf_filter: BPF filter to use on packets.
:param display_filter: Display (wireshark) filter to use.
:param only_summaries: Only produce packet summaries, much faster but includes very little information
:param decryption_key: Key used to encrypt and decrypt captured traffic.
:param encryption_type: Standard of encryption used in captured traffic (must be either 'WEP', 'WPA-PWD',
or 'WPA-PWK'. Defaults to WPA-PWK).
"""
super(InMemCapture, self).__init__(display_filter=display_filter, only_summaries=only_summaries,
from distutils.version import LooseVersion
from pyshark.capture.capture import Capture, StopCapture
DEFAULT_TIMEOUT = 30
class LinkTypes(object):
NULL = 0
ETHERNET = 1
IEEE802_5 = 6
PPP = 9
IEEE802_11 = 105
class InMemCapture(Capture):
def __init__(self, bpf_filter=None, display_filter=None, only_summaries=False,
decryption_key=None, encryption_type='wpa-pwk', decode_as=None,
disable_protocol=None, tshark_path=None, override_prefs=None, use_json=False,
linktype=LinkTypes.ETHERNET, include_raw=False, eventloop=None, custom_parameters=None,
debug=False):
"""Creates a new in-mem capture, a capture capable of receiving binary packets and parsing them using tshark.
Significantly faster if packets are added in a batch.
:param bpf_filter: BPF filter to use on packets.
:param display_filter: Display (wireshark) filter to use.
:param only_summaries: Only produce packet summaries, much faster but includes very little information
:param decryption_key: Key used to encrypt and decrypt captured traffic.
:param encryption_type: Standard of encryption used in captured traffic (must be either 'WEP', 'WPA-PWD',
or 'WPA-PWK'. Defaults to WPA-PWK).
else:
self.interfaces = [interface]
def get_parameters(self, packet_count=None):
"""
Returns the special tshark parameters to be used according to the configuration of this class.
"""
params = super(LiveCapture, self).get_parameters(packet_count=packet_count)
for interface in self.interfaces:
params += ['-i', interface]
if self.bpf_filter:
params += ['-f', self.bpf_filter]
return params
# Backwards compatibility
sniff = Capture.load_packets
def sniff_continuously(self, packet_count=None):
"""
Captures from the set interface, returning a generator which returns packets continuously.
Can be used as follows:
for packet in capture.sniff_continuously();
print 'Woo, another packet:', packet
Note: you can also call capture.apply_on_packets(packet_callback) which should have a slight performance boost.
:param packet_count: an amount of packets to capture, then stop.
"""
# Retained for backwards compatibility and to add documentation.
return self._packets_from_tshark_sync(packet_count=packet_count)