[英]Fetch port number of packet as a list using python - Scapy script
我想獲取數據包的端口號作為列表,例如:
[234,456,456,222,22]....
但不是:
[234][435][456][222][222]....
這個怎么做?
好。 因此,這可能不是最優雅的解決方案,但我認為它可以滿足您的需求。 我設置了一個字典,將多個鍵映射到多個值。 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.