如何使用Python/Scapy获取pcap数据包到达时间及会话统计信息
错误原因
你调用a.sessions()得到的每个会话值是数据包列表,列表本身没有time属性,只有列表中单个数据包对象才存储了time字段,对应该数据包的到达Unix时间戳。
解决方案
如果需要获取会话首包到达时间,直接取列表第一个元素的time属性即可,如需统计你提到的包间隔、总字节数等信息,遍历会话下的所有数据包计算即可。
可直接运行的修改后代码
from scapy.all import * from datetime import datetime pcap_file = "test.pcap" a = rdpcap(pcap_file) sessions = a.sessions() for k, packet_list in sessions.items(): tot_packets = len(packet_list) # 计算会话总字节数 tot_bytes = sum(len(pkt) for pkt in packet_list) proto, source, dir_flag, target = k.split() srcip, srcport = source.split(":") dstip, dstport = target.split(":") direction = "outbound" if dir_flag == '>' else "inbound" # 取首包到达时间,不需要可读格式可删除转换逻辑 pkttime = packet_list[0].time readable_pkttime = datetime.fromtimestamp(pkttime).strftime("%Y-%m-%d %H:%M:%S.%f") # 计算同方向相邻数据包间隔(单位:秒) inter_arrival = [] for i in range(1, tot_packets): inter_arrival.append(round(packet_list[i].time - packet_list[i-1].time, 6)) # 输出格式可按需调整 print('%s,%s,%s,%s,%s,%s,%s,%s,%s\n' % (srcip, dstip, proto, srcport, dstport, tot_packets, direction, readable_pkttime, tot_bytes)) print(f"当前会话相邻包间隔:{inter_arrival}\n")
补充说明
- 若需要获取每个数据包的单独到达时间,遍历
packet_list逐个取pkt.time即可 time字段默认是Unix时间戳,可通过datetime模块转换为任意可读格式
内容的提问来源于stack exchange,提问作者Plutoverse
相关产品推荐
相关产品推荐

