Python pyshark.LiveCapture() Examples

The following are 8 code examples of pyshark.LiveCapture(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pyshark , or try the search function .
Example #1
Source File: utils.py    From HoneyBot with MIT License 6 votes vote down vote up
def capture_on_interface(interface, name, timeout=60):
    """
    :param interface: The name of the interface on which to capture traffic
    :param name: The name of the capture file
    :param timeout: A limit in seconds specifying how long to capture traffic
    """

    if timeout < 15:
        logger.error("Timeout must be over 15 seconds.")
        return
    if not sys.warnoptions:
        warnings.simplefilter("ignore")
    start = time.time()
    widgets = [
        progressbar.Bar(marker=progressbar.RotatingMarker()),
        ' ',
        progressbar.FormatLabel('Packets Captured: %(value)d'),
        ' ',
        progressbar.Timer(),
    ]
    progress = progressbar.ProgressBar(widgets=widgets)
    capture = pyshark.LiveCapture(interface=interface, output_file=os.path.join('tmp', name))
    pcap_size = 0
    for i, packet in enumerate(capture.sniff_continuously()):
        progress.update(i)
        if os.path.getsize(os.path.join('tmp', name)) != pcap_size:
            pcap_size = os.path.getsize(os.path.join('tmp', name))
        if not isinstance(packet, pyshark.packet.packet.Packet):
            continue
        if time.time() - start > timeout:
            break
        if pcap_size > const.PT_MAX_BYTES:
            break
    capture.clear()
    capture.close()
    return pcap_size 
Example #2
Source File: pcap_sniffer.py    From black-widow with GNU General Public License v3.0 6 votes vote down vote up
def __init__(
            self,
            filters: str = None,
            src_file: str = None,
            dest_file: str = None,
            interfaces: list = None,
            limit_length: int = None,
            pkt_count: int = None,
            callback=None
    ):
        """
        Packet capture method
        :param filters: https://wiki.wireshark.org/DisplayFilters
        :param src_file: Il file .pcap da cui leggere i pacchetti ascoltati (o None, per Live sniffing)
        :param dest_file: Il file in cui scrivere il .pcap dei pacchetti ascoltati (o None)
        :param interfaces: The list of interfaces to sniff (or None, to sniff all interfaces)
        :param limit_length: The limit length of each packet field (they will be truncated), or None
        :param pkt_count: Max packets to sniff, or None
        :param callback: The callback method to call (or None) (@see PcapSniffer._user_callback_example)
        """
        if not PcapSniffer.is_executable():
            raise RuntimeError('Unable to execute pcap sniffer')
        self.count = 0  # Sniffed packets
        self.max_count = pkt_count
        # Prevents the mac manufacturer lookup sniffing
        self.filters = PcapSniffer._get_filters(filters)
        self.src_file = src_file
        self.dest_file = dest_file
        self.limit_length = limit_length
        self.user_callback = callback
        self.interfaces = interfaces
        Log.info('Analyzing filters: ' + str(self.filters))
        if self.src_file is not None:
            Log.info('Analyzing file: ' + self.src_file)
            self._capture = pyshark.FileCapture(
                input_file=self.src_file,
                display_filter=self.filters,
                output_file=self.dest_file,
                # include_raw=True,
                # use_json=True
                # debug=APP_DEBUG
            )
        else:
            Log.info('Analyzing live traffic')
            self._capture = pyshark.LiveCapture(
                interface=self.interfaces,
                display_filter=self.filters,
                output_file=self.dest_file,
                # include_raw=True,
                # use_json=True
                # debug=APP_DEBUG
            ) 
Example #3
Source File: scanner.py    From aztarna with GNU General Public License v3.0 6 votes vote down vote up
def scan_passive(self, interface: str):
        for pkg in pyshark.LiveCapture(interface=interface, display_filter='rtps'):
            print(pkg) 
Example #4
Source File: utils.py    From HoneyBot with MIT License 5 votes vote down vote up
def listen_on_interface(interface, timeout=60):
    """
    :param interface: The name of the interface on which to capture traffic
    :return: generator containing live packets
    """

    start = time.time()
    capture = pyshark.LiveCapture(interface=interface)

    for item in capture.sniff_continuously():
        if timeout and time.time() - start > timeout:
            break
        yield item 
Example #5
Source File: feeder_tshark.py    From attack_monitor with GNU General Public License v3.0 5 votes vote down vote up
def run(self):
        INTERFACE_NAME = self.get_config_option("network_interface")
        if INTERFACE_NAME is None:
            print("You didn't specify network_inteface in configuration file for feeder_tshark plugin.")
            sys.exit(0)
        elif INTERFACE_NAME == "any":
            INTERFACE_NAME = None

        try:
            cap = pyshark.LiveCapture(interface=INTERFACE_NAME, bpf_filter="udp port 53")

        # NOT WORKING
        except Exception:
            print("Cannot start capturing events with tshark. Interface choosen: {}".format(INTERFACE_NAME))
            sys.exit(0)

        try:
            for packet in cap.sniff_continuously():
                pass_mq = mq(packet, TYPE_NETWORK_PACKET, self.getName(), NiceDate.naive_datetime_localize(packet.sniff_time), generate_mq_key(packet, None), None)
                self.add_to_ultra_mq(pass_mq)
                self.global_break()

        # NOT WORKING
        except Exception as ts:
            print("Error when capturing events with tshark. Interface choosen: {}".format(INTERFACE_NAME))
            print(ts)
            sys.exit(0)

# 'add_field', 'all_fields', 'alternate_fields', 'base16_value', 'binary_value',
            # 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith',
            # 'expandtabs', 'fields', 'find', 'format', 'get_default_value',
            # 'hex_value', 'hide', 'index', 'int_value', 'isalnum', 'isalpha',
            # 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join',
            # 'ljust', 'lower', 'lstrip', 'main_field', 'name', 'partition',
            # 'pos', 'raw_value', 'replace', 'rfind', 'rindex', 'rjust',
            # 'rpartition', 'rsplit', 'rstrip', 'show', 'showname',
            # 'showname_key', 'showname_value', 'size', 'split',
            # 'splitlines', 'startswith', 'strip', 'swapcase',
            # 'title', 'translate', 'unmaskedvalue', 'upper',
            # 'zfill'] 
Example #6
Source File: dcept.py    From dcept with GNU General Public License v3.0 5 votes vote down vote up
def kerbsniff(interface, username, domain, realm):

	logging.info("kerbsniff: Looking for %s\%s on %s" % (domain,username,interface))
	
	filtered_cap = pyshark.LiveCapture(interface, bpf_filter='tcp port 88')
	packet_iterator = filtered_cap.sniff_continuously
	
	# Loop infinitely over packets if in continuous mode
	for packet in packet_iterator():

		# Is this packet kerberos?
		kp = None
		encTimestamp = None
		try:
			kp = packet['kerberos']

			# Extract encrypted timestamp for Kerberos Preauthentication packets
			# that conatin honeytoken domain\username
			encTimestamp = kerb_handler(kp,domain,username)
		except KeyError as e:
			pass
		
		

		# Only attempt to decrypt a password or notify master if we find an encrypted timestamp
		if encTimestamp:

			if config.master_node:
				notifyMaster(username, domain, encTimestamp)
			else:
				cracker.enqueueJob(username, domain, encTimestamp, passwordHit) 
Example #7
Source File: generic_sniffer.py    From peniot with MIT License 5 votes vote down vote up
def start_live_capture(self):
        """
        Start capture procedure of packets over listener
        :return: None since captured packets are saved internally
        """
        capture = pyshark.LiveCapture(interface=self.interface, use_json=self.use_json, include_raw=self.include_raw,
                                      output_file=self.output_pcap_filename, display_filter=self.display_filter)
        capture.sniff(timeout=self.timeout)
        self.captured_packets = capture._packets
        logger.info("{0} packets are captured.".format(len(self.captured_packets)))
        capture.close() 
Example #8
Source File: metrics.py    From PySyft with Apache License 2.0 4 votes vote down vote up
def get_packets(
        timeout=50,
        interface=None,
        bpf_filter=None,
        display_filter="tcp.port == 80",
        tshark_path=None,
        output_file=None,
    ):
        """
        Returns the captured packets of the transmitted data using Wireshark.

        Args:
        timeout: An integer. Set for sniffing with tshark. Default to 50 seconds in this setup.
        interface: A string. Name of the interface to sniff on.
        bpf_filter: A string. The capture filter in bpf syntax 'tcp port 80'. Needs to be changed
                    to match filter for the traffic sent. Not to be confused with the display
                    filters (e.g. tcp.port == 80). The former are much more limited and is used to
                    restrict the size of a raw packet capture, whereas the latter is used to hide
                    some packets from the packet list. More info can be found at
                    https://wiki.wireshark.org/CaptureFilters.
        display_filter: A string. Default to 'tcp.port == 80' (assuming this is the port of the
                        'WebsocketClientWorker'). Please see notes for 'bpf_filter' for details
                        regarding differences. More info can be found at
                        https://wiki.wireshark.org/DisplayFilters.
        tshark_path: Path to the tshark binary. E.g. '/usr/local/bin/tshark'.
        output_file: A string. Path including the output file name is to saved.
                     E.g. '/tmp/mycapture.cap'

        Returns:
        catpure: A 'pyshark.capture.live_capture.LiveCapture' object. Of packets sent
                 over WebSockets.
        length: An integer. The number of packets captured at the network interface.
        """
        capture_output = []
        if interface is None:
            raise Exception("Please provide the interface used.")
        else:
            capture = pyshark.LiveCapture(
                interface=interface,
                bpf_filter=bpf_filter,
                tshark_path=tshark_path,
                output_file=output_file,
            )
            capture.sniff(timeout=timeout)
            length = len(capture)
            return capture, length