简体   繁体   English

使用python获取数据包的端口号作为列表-Scapy脚本

[英]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 获取数据包的源地址和端口号-Scapy脚本

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. IP映射到映射到计数器的多个端口。 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. 在测试.pcap是否不是从那些日期开始之前,请删除该检查或更改时间值。 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): 最简单的方法是通过可理解的方式构建列表(假设plist是您的数据包列表):

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: 当然,如果要使用不同的端口,则可以使用一set

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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