1

教程和本文档描述了如何在实时界面中捕获数据包。但是,您必须指定一个限制(数据包数量或超时)才能开始嗅探:

capture = pyshark.LiveCapture(interface='eth0')
capture.sniff(timeout=50)

或者

cap.sniff(packet_count=50)

我的问题:有没有办法在不指定限制的情况下继续捕获数据包?

4

1 回答 1

3

我可以使用 sniff_continuously() 连续嗅探数据包。下面是一些用于连续处理来自网络接口的 TCP 数据包的示例代码。

def capture_live_packets(network_interface):
    capture = pyshark.LiveCapture(interface=network_interface)
    for raw_packet in capture.sniff_continuously():
        print(filter_all_tcp_traffic_file(raw_packet))

def get_packet_details(packet):
    """
    This function is designed to parse specific details from an individual packet.
    :param packet: raw packet from either a pcap file or via live capture using TShark
    :return: specific packet details
    """
    protocol = packet.transport_layer
    source_address = packet.ip.src
    source_port = packet[packet.transport_layer].srcport
    destination_address = packet.ip.dst
    destination_port = packet[packet.transport_layer].dstport
    packet_time = packet.sniff_time
    return f'Packet Timestamp: {packet_time}' \
           f'\nProtocol type: {protocol}' \
           f'\nSource address: {source_address}' \
           f'\nSource port: {source_port}' \
           f'\nDestination address: {destination_address}' \
           f'\nDestination port: {destination_port}\n'


def filter_all_tcp_traffic_file(packet):
    """
    This function is designed to parse all the Transmission Control Protocol(TCP) packets
    :param packet: raw packet
    :return: specific packet details
    """
    if hasattr(packet, 'tcp'):
       results = get_packet_details(packet)
       return results

capture_live_packets('en0')
于 2020-04-14T14:13:45.410 回答