如何在实时数据包嗅探上添加计数器

how to add a counter on live packets sniffing

我希望每次相同的数据包到达时更新计数并打印

# from collections import Counter

capture = pyshark.LiveCapture(interface='wlo2', bpf_filter='arp')
capture.sniff(timeout=5)

keys = {}

e_mac = '00:00:00:00:00:00' or 'ff:ff:ff:ff:ff:ff'
already_seen = []
count = 0

for packet in capture:
    keys['ip'] = packet.arp.dst_proto_ipv4
    keys['mac'] = packet.arp.dst_hw_mac
    seen = keys['mac'], keys['ip']
    
    if keys['mac'] != e_mac:
        if seen not in already_seen:
            already_seen.append(seen)

            print(packet.sniff_time, keys['mac'], keys['ip'])

目前我收到了这个输出

2021-12-06 18:59:55.325859 28:d1:27:1a:12:c0 192.168.1.3
2021-12-06 18:59:58.704726 f8:c4:f3:56:a3:70 192.168.1.1
2021-12-06 19:00:02.286922 ff:ff:ff:ff:ff:ff 192.168.1.1
2021-12-06 19:02:15.854700 44:af:28:2c:6d:6b 192.168.1.195
2021-12-06 19:07:02.440235 90:e8:68:f2:00:c1 192.168.1.13
Dec 06 16:07:45  2(i.e. times i received) 28:d1:27:1a:12:c0 192.168.1.3

Dec 06 16:08:01  4 f8:c4:f3:56:a3:70 192.168.1.1

我想要的实际输出就像计数将仅针对特定数据包更新我收到它的次数,如果有新的 mac 出现,它将维护该数据包的单独计数器:

您必须在 for-loop 之前创建空 Counter(),然后在 for-loop`

中更新此计数器

Minimla 工作代码:

而不是 YOUR_MACYOUR_IP 您必须从包中获取值。

from collections import Counter

# --- before loop ---

count = Counter()

# --- loop ---

for x in range(5):
    mac = 'YOUR_MAC'
    ip  = 'YOUR_IP'
    count.update( [(mac, ip)] )  # it has to be list with tuple
    print(count[ (mac, ip) ], mac, ip)

结果:

1 YOUR_MAC YOUR_IP
2 YOUR_MAC YOUR_IP
3 YOUR_MAC YOUR_IP
4 YOUR_MAC YOUR_IP
5 YOUR_MAC YOUR_IP