简体   繁体   中英

Fetch port number of packet as a list using python - Scapy script

I want to fetch port number of packet as a list, like:

[234,456,456,222,22]....

but not as:

[234][435][456][222][222]....

How to do this?

Fetch source address and port number of packet - Scapy script

Ok. So this may not be the most elegant solution but I think it meets what you're looking for. I set up a dictionary that maps multiple keys to multiple values. The IP maps to multiple Ports which is mapped to a counter. The resulting dictionary contains the info. The packets are evaluated against the dates in your post. Either remove that check or change the time values before testing if your .pcap isn't from those dates. Hope this helps.

from scapy.all import *

ips = {}
pcap = rdpcap('test_pcap.pcap')

def build_dict(pkt):
    port_count = 1

    if pkt.haslayer(IP):
        ip = pkt[IP].src
        if pkt.haslayer(UDP) or pkt.haslayer(TCP):
            port = pkt.sport
            if ip in ips:  # Checks to see if the IP is already there
                if port in ips[ip]:  # Checks to see if the port is already there.
                    port_count += ips[ip][port] #If so, increments the counter by 1
            ips.setdefault(ip, {})[port] = port_count # Writes to the dictionary

for pkt in pcap:
    time = pkt.time
    if time > 1484481600 and time < 1484827200: # Checks to see if the packet is within the date range
        build_dict(pkt)
    else: pass

for k, v in ips.items():
    print(k, v)

The easiest way is to build the list via iterable comprehension (assuming plist is your packet list):

ports = [port for pkt in plist if UDP in pkt or TCP in pkt
         for port in [pkt.sport, pkt.dport]]

Of course, you can use a set if you want the distinct ports used:

ports = {port for pkt in plist if UDP in pkt or TCP in pkt
         for port in [pkt.sport, pkt.dport]}

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