简体   繁体   中英

Scapy extract IP address with no repetitions

I am trying to extract the destination IP address then save this in a dictionary but i only want it once

Input

from scapy.all import *

pkts = rdpcap('example.pcap')

test = ""
for pkt in pkts:
    temp = pkt.sprintf("%IP.dst%",)
    test = test + temp

print(test)


Currently my output is like this

??,????,????,????,??0.0.0.0,255.255.255.255192.168.1.1,192.168.1.2380.0.0.0,255.255.255.255192.168.1.1,192.168.1.238192.168.1.1,192.168.1.2380.0.0.0,255.255.255.255192.168.1.1,192.168.1.238??,????,????,????,????,??192.168.1.238,192.168.1.1192.168.1.1,192.168.1.238192.168.1.238,89.30.121.15089.30.121.150,192.168.1.238192.168.1.238,89.30.121.150192.168.1.238,89.30.121.15089.30.121.150,192.168.1.238192.168.1.238,89.30.121.150192.16

What I want is the output to look like this and I want the destination IP address only with no repeats

89.30.121.150
198.50.110.244
89.30.121.14
89.30.121.23

What I do get in the output is a massive list of IP addresses instead I only want the destination IP address but only ONCE(no repetitions) not for each packet

I have also tried this but this freezes?

def print_summary(pkt):
    if IP in pkt:
        ip_dst=pkt[IP].dst
    print(ip_dst)

sniff(offline=pkts, filter="ip",prn=print_summary)

Can anyone think of a quicker solution to extract IP addresses from larger PCAP files using Scapy

If you want to put in dictionary you should use dictionary.

You getting repeated value because you are not saving it into python dict.

Here is one way to keep src-->dest ip without repeating by modifying your code:

from scapy.all import *

pkts = rdpcap('example.pcap')

dic = {}
for pkt in pkts:
    temp = pkt.sprintf("%IP.dst%")
    dic[temp] = 1

for ip in dic.keys():
    print(ip)

output:

192.168.1.1
192.37.115.0
192.168.1.2
212.242.33.35
192.168.1.251
147.137.21.94
147.137.21.122
147.234.1.253

One of the fastest method is:

from scapy.all import *

IP.payload_guess = []

ips = set(p[IP].dst for p in PcapReader('example.pcap') if IP in p)

for ip in ips:
    print(ip)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM