繁体   English   中英

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

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

我想获取数据包的端口号作为列表,例如:

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

但不是:

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

这个怎么做?

获取数据包的源地址和端口号-Scapy脚本

好。 因此,这可能不是最优雅的解决方案,但我认为它可以满足您的需求。 我设置了一个字典,将多个键映射到多个值。 IP映射到映射到计数器的多个端口。 生成的词典包含信息。 将根据帖子中的日期评估数据包。 在测试.pcap是否不是从那些日期开始之前,请删除该检查或更改时间值。 希望这可以帮助。

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)

最简单的方法是通过可理解的方式构建列表(假设plist是您的数据包列表):

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

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