Skip to content

Commit

Permalink
Unified conventions
Browse files Browse the repository at this point in the history
  • Loading branch information
KimiNewt committed Sep 1, 2019
1 parent 2488041 commit 3e8846f
Show file tree
Hide file tree
Showing 5 changed files with 68 additions and 99 deletions.
48 changes: 15 additions & 33 deletions src/pyshark/capture/capture.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,16 +26,12 @@ class RawMustUseJsonException(Exception):


class StopCapture(Exception):
"""
Exception that the user can throw anywhere in packet-handling to stop the capture process.
"""
"""Exception that the user can throw anywhere in packet-handling to stop the capture process."""
pass


class Capture(object):
"""
Base class for packet captures.
"""
"""Base class for packet captures."""
DEFAULT_BATCH_SIZE = 2 ** 16
SUMMARIES_BATCH_SIZE = 64
DEFAULT_LOG_LEVEL = logging.CRITICAL
Expand Down Expand Up @@ -83,8 +79,7 @@ def __init__(self, display_filter=None, only_summaries=False, eventloop=None,
% ", ".join(self.SUPPORTED_ENCRYPTION_STANDARDS))

def __getitem__(self, item):
"""
Gets the packet in the given index.
"""Gets the packet in the given index.
:param item: packet index
:return: Packet object.
Expand Down Expand Up @@ -112,14 +107,12 @@ def clear(self):
self._current_packet = 0

def reset(self):
"""
Starts iterating packets from the first one.
"""
"""Starts iterating packets from the first one."""
self._current_packet = 0

def load_packets(self, packet_count=0, timeout=None):
"""
Reads the packets from the source (cap, interface, etc.) and adds it to the internal list.
"""Reads the packets from the source (cap, interface, etc.) and adds it to the internal list.
If 0 as the packet_count is given, reads forever
:param packet_count: The amount of packets to add to the packet list (0 to read forever)
Expand All @@ -140,9 +133,7 @@ def keep_packet(pkt):
pass

def set_debug(self, set_to=True, log_level=logging.DEBUG):
"""
Sets the capture to debug mode (or turns it off if specified).
"""
"""Sets the capture to debug mode (or turns it off if specified)."""
if set_to:
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s"))
Expand All @@ -151,9 +142,7 @@ def set_debug(self, set_to=True, log_level=logging.DEBUG):
self.debug = set_to

def _setup_eventloop(self):
"""
Sets up a new eventloop as the current one according to the OS.
"""
"""Sets up a new eventloop as the current one according to the OS."""
if os.name == "nt":
self.eventloop = asyncio.ProactorEventLoop()
else:
Expand Down Expand Up @@ -225,8 +214,8 @@ def _extract_tag_from_data(self, data, tag_name=b"packet"):
return None, data

def _packets_from_tshark_sync(self, packet_count=None, existing_process=None):
"""
Returns a generator of packets.
"""Returns a generator of packets.
This is the sync version of packets_from_tshark. It wait for the completion of each coroutine and
reimplements reading packets in a sync way, yielding each packet as it arrives.
Expand Down Expand Up @@ -259,8 +248,8 @@ def _packets_from_tshark_sync(self, packet_count=None, existing_process=None):
self.eventloop.run_until_complete(self._cleanup_subprocess(tshark_process))

def apply_on_packets(self, callback, timeout=None, packet_count=None):
"""
Runs through all packets and calls the given callback (a function) with each one as it is read.
"""Runs through all packets and calls the given callback (a function) with each one as it is read.
If the capture is infinite (i.e. a live capture), it will run forever, otherwise it will complete after all
packets have been read.
Expand Down Expand Up @@ -291,7 +280,6 @@ async def packets_from_tshark(self, packet_callback, packet_count=None, close_ts
finally:
if close_tshark:
await self.close_async()
#yield From(self._cleanup_subprocess(tshark_process))

async def _go_through_packets_from_fd(self, fd, packet_callback, packet_count=None):
"""A coroutine which goes through a stream and calls a given callback for each XML packet seen in it."""
Expand Down Expand Up @@ -384,9 +372,7 @@ def _get_tshark_version(self):
return self.__tshark_version

async def _get_tshark_process(self, packet_count=None, stdin=None):
"""
Returns a new tshark process with previously-set parameters.
"""
"""Returns a new tshark process with previously-set parameters."""
if self.use_json:
output_type = "json"
if not tshark_supports_json(self._get_tshark_version()):
Expand Down Expand Up @@ -414,9 +400,7 @@ def _created_new_process(self, parameters, process, process_name="TShark"):
self._running_processes.add(process)

async def _cleanup_subprocess(self, process):
"""
Kill the given process and properly closes any pipes connected to it.
"""
"""Kill the given process and properly closes any pipes connected to it."""
if process.returncode is None:
try:
process.kill()
Expand Down Expand Up @@ -451,9 +435,7 @@ def __exit__(self, exc_type, exc_val, exc_tb): self.close()
async def __aexit__(self, exc_type, exc_val, exc_tb): await self.close_async()

def get_parameters(self, packet_count=None):
"""
Returns the special tshark parameters to be used according to the configuration of this class.
"""
"""Returns the special tshark parameters to be used according to the configuration of this class."""
params = []
if self._capture_filter:
params += ["-f", self._capture_filter]
Expand Down
23 changes: 10 additions & 13 deletions src/pyshark/capture/file_capture.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,14 @@


class FileCapture(Capture):
"""
A class representing a capture read from a file.
"""
"""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,
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.
"""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!)
Expand Down Expand Up @@ -47,15 +44,15 @@ def __init__(self, input_file=None, keep_packets=True, display_filter=None, only
self.input_filename = input_file.name
if not os.path.exists(self.input_filename):
raise FileNotFoundError(
'[Errno 2] No such file or directory: '
"[Errno 2] No such file or directory: "
+ str(self.input_filename)
)
self.keep_packets = keep_packets
self._packet_generator = self._packets_from_tshark_sync()

def next(self):
"""
Returns the next packet in the cap.
"""Returns the next packet in the cap.
If the capture's keep_packets flag is True, will also keep it in the internal packet list.
"""
if not self.keep_packets:
Expand All @@ -74,14 +71,14 @@ def __getitem__(self, packet_index):
self.next()
except StopIteration:
# We read the whole file, and there's still not such packet.
raise KeyError('Packet of index %d does not exist in capture' % packet_index)
raise KeyError("Packet of index %d does not exist in capture" % packet_index)
return super(FileCapture, self).__getitem__(packet_index)

def get_parameters(self, packet_count=None):
return super(FileCapture, self).get_parameters(packet_count=packet_count) + ['-r', self.input_filename]
return super(FileCapture, self).get_parameters(packet_count=packet_count) + ["-r", self.input_filename]

def __repr__(self):
if self.keep_packets:
return '<%s %s>' % (self.__class__.__name__, self.input_filename)
return "<%s %s>" % (self.__class__.__name__, self.input_filename)
else:
return '<%s %s (%d packets)>' % (self.__class__.__name__, self.input_filename, len(self._packets))
return "<%s %s (%d packets)>" % (self.__class__.__name__, self.input_filename, len(self._packets))
21 changes: 8 additions & 13 deletions src/pyshark/capture/inmem_capture.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ def __init__(self, bpf_filter=None, display_filter=None, only_summaries=False,
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.
"""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.
Expand Down Expand Up @@ -56,9 +56,7 @@ def __init__(self, bpf_filter=None, display_filter=None, only_summaries=False,
self._current_tshark = None

def get_parameters(self, packet_count=None):
"""
Returns the special tshark parameters to be used according to the configuration of this class.
"""
"""Returns the special tshark parameters to be used according to the configuration of this class."""
params = super(InMemCapture, self).get_parameters(packet_count=packet_count)
params += ['-i', '-']
return params
Expand Down Expand Up @@ -93,8 +91,7 @@ def _write_packet(self, packet):
self._current_tshark.stdin.write(packet)

def parse_packet(self, binary_packet):
"""
Parses a single binary packet and returns its parsed version.
"""Parses a single binary packet and returns its parsed version.
DOES NOT CLOSE tshark. It must be closed manually by calling close() when you're done
working with it.
Expand All @@ -103,17 +100,15 @@ def parse_packet(self, binary_packet):
return self.parse_packets([binary_packet])[0]

def parse_packets(self, binary_packets):
"""
Parses binary packets and return a list of parsed packets.
"""Parses binary packets and return a list of parsed packets.
DOES NOT CLOSE tshark. It must be closed manually by calling close() when you're done
working with it.
"""
return asyncio.get_event_loop().run_until_complete(self.parse_packets_async(binary_packets))

async def parse_packets_async(self, binary_packets):
"""
A coroutine which parses binary packets and return a list of parsed packets.
"""A coroutine which parses binary packets and return a list of parsed packets.
DOES NOT CLOSE tshark. It must be closed manually by calling close() when you're done
working with it.
Expand Down Expand Up @@ -169,8 +164,8 @@ def feed_packet(self, binary_packet, linktype=LinkTypes.ETHERNET):
return pkt

def feed_packets(self, binary_packets, linktype=LinkTypes.ETHERNET):
"""
Gets a list of binary packets, parses them using tshark and returns their parsed values.
"""Gets a list of binary packets, parses them using tshark and returns their parsed values.
Keeps the packets in the internal packet list as well.
By default, assumes the packets are ethernet packets. For another link type, supply the linktype argument (most
Expand Down
24 changes: 10 additions & 14 deletions src/pyshark/capture/live_capture.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,14 @@


class LiveCapture(Capture):
"""
Represents a live capture on a network interface.
"""
"""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.
"""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.
Expand Down Expand Up @@ -49,8 +46,8 @@ def __init__(self, interface=None, bpf_filter=None, display_filter=None, only_su
self.bpf_filter = bpf_filter
self.monitor_mode = monitor_mode

if sys.platform == 'win32' and monitor_mode:
raise WindowsError('Monitor mode is not supported by the Windows platform')
if sys.platform == "win32" and monitor_mode:
raise WindowsError("Monitor mode is not supported by the Windows platform")

if interface is None:
self.interfaces = get_tshark_interfaces(tshark_path)
Expand All @@ -65,7 +62,7 @@ def get_parameters(self, packet_count=None):
"""
params = super(LiveCapture, self).get_parameters(packet_count=packet_count)
# Read from STDIN
params += ['-r', '-']
params += ["-r", "-"]
return params

def _get_dumpcap_parameters(self):
Expand All @@ -75,11 +72,11 @@ def _get_dumpcap_parameters(self):
# Tshark versions older than 2.5 don't support pcapng. This flag forces dumpcap to output pcap.
params += ["-P"]
if self.bpf_filter:
params += ['-f', self.bpf_filter]
params += ["-f", self.bpf_filter]
if self.monitor_mode:
params += ['-I']
params += ["-I"]
for interface in self.interfaces:
params += ['-i', interface]
params += ["-i", interface]
# Write to STDOUT
params += ["-w", "-"]
return params
Expand All @@ -101,12 +98,11 @@ async def _get_tshark_process(self, packet_count=None, stdin=None):
sniff = Capture.load_packets

def sniff_continuously(self, packet_count=None):
"""
Captures from the set interface, returning a generator which returns packets continuously.
"""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
print('Woo, another packet:', packet)
Note: you can also call capture.apply_on_packets(packet_callback) which should have a slight performance boost.
Expand Down
Loading

0 comments on commit 3e8846f

Please sign in to comment.