在Pyshark中连续捕获数据包

时间:2019-07-18 16:55:48

标签: python-3.x sniffing pyshark

tutorial和此documentation描述了如何在实时接口中捕获数据包。 但是,您必须指定一个限制(数据包数量或超时)才能开始嗅探:

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

OR

cap.sniff(packet_count=50)

我的问题:是否可以在不指定限制的情况下继续捕获数据包?

1 个答案:

答案 0 :(得分:1)

我可以使用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')