Sniff packets and print them calling pkt.show(), a bit like text wireshark
507943
def tshark(*args,**kargs):
    """"""
    sniff(prn=lambda x: x.display(),*args,**kargs)
971429
def simple_trace_to_wkt_linestring(trace):
    '''
    
    '''
    trace_str = ""
    for point in trace:
        trace_str += ' %s %s,' % (point.longitude, point.latitude)
    trace_str = trace_str.lstrip(' ')
    return 'LINESTRING (' + trace_str.rstrip(',') + ')'
60420
def pretty_print(self):
        
        msg = "Source: " + str(self._source) + "\n"
        msg += "Destination: " + str(self._destination) + "\n"
        inv_types = {v: k for k, v in defines.Types.items()}
        msg += "Type: " + str(inv_types[self._type]) + "\n"
        msg += "MID: " + str(self._mid) + "\n"
        if self._code is None:
            self._code = 0

        msg += "Code: " + str(defines.Codes.LIST[self._code].name) + "\n"
        msg += "Token: " + str(self._token) + "\n"
        for opt in self._options:
            msg += str(opt)
        msg += "Payload: " + "\n"
        msg += str(self._payload) + "\n"
        return msg
134048
def handle(self, pkt, raddress, rport):
        ""
        if isinstance(pkt, TftpPacketACK):
            log.debug("Received ACK for packet %d" % pkt.blocknumber)
            # Is this an ack to the one we just sent?
            if self.context.next_block == pkt.blocknumber:
                if self.context.pending_complete:
                    log.info("Received ACK to final DAT, we're done.")
                    return None
                else:
                    log.debug("Good ACK, sending next DAT")
                    self.context.next_block += 1
                    log.debug("Incremented next_block to %d",
                        self.context.next_block)
                    self.context.pending_complete = self.sendDAT()

            elif pkt.blocknumber < self.context.next_block:
                log.warning("Received duplicate ACK for block %d"
                    % pkt.blocknumber)
                self.context.metrics.add_dup(pkt)

            else:
                log.warning("Oooh, time warp. Received ACK to packet we "
                         "didn't send yet. Discarding.")
                self.context.metrics.errors += 1
            return self
        elif isinstance(pkt, TftpPacketERR):
            log.error("Received ERR packet from peer: %s" % str(pkt))
            raise TftpException("Received ERR packet from peer: %s" % str(pkt))
        else:
            log.warning("Discarding unsupported packet: %s" % str(pkt))
            return self
46332
def mavlink_packet(self, m):
        ''''''
        if m.get_type() == 'SERIAL_CONTROL':
            data = m.data[:m.count]
            if m.count > 0:
                s = ''.join(str(chr(x)) for x in data)
                if self.mpstate.system == 'Windows':
                    # strip nsh ansi codes
                    s = s.replace("\033[K","")
                sys.stdout.write(s)
                self.last_packet = time.time()
1058950
def pull(self):
        """"""

        # For each packet in the pcap process the contents
        for item in self.input_stream:

            # Print out the timestamp in UTC
            print('%s -' % item['timestamp'], end='')

            # Transport info
            if item['transport']:
                print(item['transport']['type'], end='')

            # Print out the Packet info
            packet_type = item['packet']['type']
            print(packet_type, end='')
            packet = item['packet']
            if packet_type in ['IP', 'IP6']:
                # Is there domain info?
                if 'src_domain' in packet:
                    print('%s(%s) --> %s(%s)' % (net_utils.inet_to_str(packet['src']), packet['src_domain'],
                                                 net_utils.inet_to_str(packet['dst']), packet['dst_domain']), end='')
                else:
                    print('%s --> %s' % (net_utils.inet_to_str(packet['src']), net_utils.inet_to_str(packet['dst'])), end='')
            else:
                print(str(packet))

            # Only include application if we have it
            if item['application']:
                print('Application: %s' % item['application']['type'], end='')
                print(str(item['application']), end='')

            # Just for newline
            print()
1018425
def print_flow_info(flow):
    """"""
    print('Flow %s (%s)-- Packets:%d Bytes:%d Payload: %s...' % (flow['flow_id'], flow['direction'], len(flow['packet_list']),
                                                              len(flow['payload']), repr(flow['payload'])[:30]))
1010528
def read(self):
        

        data = self.dev.read()

        if len(data) == 0:
            self.log.warning("READ : Nothing received")
            return

        if data == b'\x00':
            self.log.warning("READ : Empty packet (Got \\x00)")
            return

        pkt = bytearray(data)
        data = self.dev.read(pkt[0])
        pkt.extend(bytearray(data))

        self.log.info("READ : %s" % self.format_packet(pkt))
        self.do_callback(pkt)
        return pkt
1058840
def print_debug(self, msg):
        """"""
        assert isinstance(msg, bytes)
        state = STATE_NAMES[self.state].encode()
        console_output(b'[dbg] ' + self.display_name.encode() + b'[' + state +
                       b']: ' + msg + b'\n')
516886
def print_bytes(byte_str):
    """"""
    if isinstance(byte_str, str):
        print(byte_str)
    else:
        print(str(byte_str, encoding='utf8'))
146547
def parse_packets(self, binary_packets):
        
        if not binary_packets:
            raise ValueError("Must supply at least one packet")
        parsed_packets = []

        if not self._current_tshark:
            self.eventloop.run_until_complete(self._get_tshark_process())
        for binary_packet in binary_packets:
            self._write_packet(binary_packet)

        def callback(pkt):
            parsed_packets.append(pkt)
            if len(parsed_packets) == len(binary_packets):
                raise StopCapture()

        self.eventloop.run_until_complete(self._get_parsed_packet_from_tshark(callback))
        return parsed_packets
214743
def handle_raw_tx_packet(self, writer, raw_packet):
        """"""
        peer = writer.get_extra_info('peername')
        log.debug(' %s:%s: processing data: %s', peer[0], peer[1], raw_packet)
        packet = None
        try:
            packet = decode_tx_packet(raw_packet)
        except:
            log.exception(' %s:%s: failed to parse packet: %s',
                          peer[0], peer[1], packet)

        log.debug(' %s:%s: decoded packet: %s', peer[0], peer[1], packet)
        if self.protocol and packet:
            if not ';PING;' in raw_packet:
                log.info(' %s:%s: forwarding packet %s to RFLink', peer[0], peer[1], raw_packet)
            else:
                log.debug(' %s:%s: forwarding packet %s to RFLink', peer[0], peer[1], raw_packet)
            yield from self.forward_packet(writer, packet, raw_packet)
        else:
            log.warning(' %s:%s: no valid packet %s', peer[0], peer[1], packet)
882766
def decode_file(fname):
    """"""
    if _debug: decode_file._debug("decode_file %r", fname)

    if not pcap:
        raise RuntimeError("failed to import pcap")

    # create a pcap object, reading from the file
    p = pcap.pcap(fname)

    # loop through the packets
    for i, (timestamp, data) in enumerate(p):
        try:
            pkt = decode_packet(data)
            if not pkt:
                continue
        except Exception as err:
            if _debug: decode_file._debug("    - exception decoding packet %d: %r", i+1, err)
            continue

        # save the packet number (as viewed in Wireshark) and timestamp
        pkt._number = i + 1
        pkt._timestamp = timestamp

        yield pkt
1372072
def encode(self, b64=False):
        """"""
        encoded_payload = b''
        for pkt in self.packets:
            encoded_packet = pkt.encode(b64=b64)
            packet_len = len(encoded_packet)
            if b64:
                encoded_payload += str(packet_len).encode('utf-8') + b':' + \
                    encoded_packet
            else:
                binary_len = b''
                while packet_len != 0:
                    binary_len = six.int2byte(packet_len % 10) + binary_len
                    packet_len = int(packet_len / 10)
                if not pkt.binary:
                    encoded_payload += b'\0'
                else:
                    encoded_payload += b'\1'
                encoded_payload += binary_len + b'\xff' + encoded_packet
        return encoded_payload
541064
def _scapy_read_frame(self):
        """"""
        from pcapkit.toolkit.scapy import (ipv4_reassembly, ipv6_reassembly,
                                           packet2chain, packet2dict, tcp_reassembly,
                                           tcp_traceflow)

        # fetch Scapy packet
        packet = next(self._extmp)

        # verbose output
        self._frnum += 1
        self._proto = packet2chain(packet)
        if self._flag_v:
            print(f' - Frame {self._frnum:>3d}: {self._proto}')

        # write plist
        frnum = f'Frame {self._frnum}'
        if not self._flag_q:
            info = packet2dict(packet)
            if self._flag_f:
                ofile = self._ofile(f'{self._ofnm}/{frnum}.{self._fext}')
                ofile(info, name=frnum)
            else:
                self._ofile(info, name=frnum)

        # record frames
        if self._flag_d:
            # setattr(packet, 'packet2dict', packet2dict)
            # setattr(packet, 'packet2chain', packet2chain)
            self._frame.append(packet)

        # record fragments
        if self._ipv4:
            flag, data = ipv4_reassembly(packet, count=self._frnum)
            if flag:
                self._reasm[0](data)  # pylint: disable=E1102
        if self._ipv6:
            flag, data = ipv6_reassembly(packet, count=self._frnum)
            if flag:
                self._reasm[1](data)  # pylint: disable=E1102
        if self._tcp:
            flag, data = tcp_reassembly(packet, count=self._frnum)
            if flag:
                self._reasm[2](data)  # pylint: disable=E1102

        # trace flows
        if self._flag_t:
            flag, data = tcp_traceflow(packet, count=self._frnum)
            if flag:
                self._trace(data)

        return packet
757801
def decap(self, orig_pkt):
        """"""
        if orig_pkt.name != Ether().name or orig_pkt.payload.name != MACsec().name:  # noqa: E501
            raise TypeError('cannot decapsulate MACsec packet, must be Ethernet/MACsec')  # noqa: E501
        packet = copy.deepcopy(orig_pkt)
        prev_layer = packet[MACsec].underlayer
        prev_layer.type = packet[MACsec].type
        next_layer = packet[MACsec].payload
        del prev_layer.payload
        if prev_layer.name == Ether().name:
            return Ether(raw(prev_layer / next_layer))
        return prev_layer / next_layer
779512
def net_send(out_data, conn):
    '''  '''
    print('Sending {} bytes'.format(len(out_data)))
    conn.send(out_data)