python - 计算源 IP 向目标 IP 发送数据包的次数
问题描述
所以这是我的代码:
pkt = PcapReader(r'C:\Users\snoopgrapes\Desktop\evidence-packet-analysis.pcap')
srce = []
dstn = []
dict = {}
for p in pkt:
if IP in p:
src = p[IP].src
dst = p[IP].dst
srce.append(str(src))
dstn.append(str(dst))
我想计算源 IP 向目标 IP 地址发送数据包的次数。我已经能够将这些对添加到单独的列表中。我也可以合并两个列表。我还能够将 IP 对添加到字典中。如何计算 SRC IP 发送到 DST IP 的次数并将结果存储在字典中?
例子:
{50: 192.168.1.10, 10.10.10.50, 35:172.16.10.1,172.16.255.254}
解决方案
您明确要求将字典作为结果对象——使用 a 可能是有意义的,Counter
因为您正在计数。即使您需要 a dict
,计数器也可以简单地转换为 1。我在这篇文章的末尾附上了一个例子。
字典
但是,要使用字典显式执行此操作,您可以使用defaultdict
带有 ( source
, destination
) 对的 a 作为键,并为每对增加存储的数字:
from collections import defaultdict
# ...
counts = defaultdict(int)
for packet in packets:
if IP in packet:
source = packet[IP].src
destination = packet[IP].dst
counts[(source, destination)] += 1
最小的工作示例:
from collections import defaultdict
class ObjectDict(dict):
def __getattr__(self, key):
if key in self:
return self[key]
IP = "IP"
packets = [
{
"IP": ObjectDict({
"src": "192.168.1.1",
"dst": "192.168.1.1",
}),
},
{
"IP": ObjectDict({
"src": "192.168.1.1",
"dst": "192.168.1.1",
}),
},
{
"IP": ObjectDict({
"src": "192.168.1.2",
"dst": "192.168.1.1",
}),
},
{
"IP": ObjectDict({
"src": "192.168.1.1",
"dst": "192.168.1.2",
}),
},
]
counts = defaultdict(int)
for packet in packets:
if IP in packet:
source = packet[IP].src
destination = packet[IP].dst
counts[(source, destination)] += 1
print(dict(counts))
输出:
{('192.168.1.1', '192.168.1.1'): 2, ('192.168.1.2', '192.168.1.1'): 1, ('192.168.1.1', '192.168.1.2'): 1}
如果 usingdefaultdict
不是一个选项,您只需将添加行替换为:
counts[(source, destination)] = counts.get((source, destination), 0) + 1
利用可用于的默认值dict.get()
柜台
要使用 a Counter
,你可以这样做
# assume same setup as above
counter_generator = ((p[IP].src, p[IP].dst) for p in packets if IP in p)
counts = Counter(counter_generator)
print(counts)
print()
print(dict(counts))
输出:
Counter({('192.168.1.1', '192.168.1.1'): 2, ('192.168.1.2', '192.168.1.1'): 1, ('192.168.1.1', '192.168.1.2'): 1})
{('192.168.1.1', '192.168.1.1'): 2, ('192.168.1.2', '192.168.1.1'): 1, ('192.168.1.1', '192.168.1.2'): 1}
推荐阅读
- ruby-on-rails - Rails Ransack gem:仅使用一个选择选项搜索多个值
- python - (找到 5 位的第一个实例)'TypeError:只能将 str(不是“re.Pattern”)连接到 str'
- javascript - 如何将包含坐标的变量传递给geojson“坐标”字段?
- python - 尝试绘制多项式时,Matplotlib 正在绘制一条“之字形”线
- ruby-on-rails - Rubocop 线长度太长,如何缩短给定线?
- python - 如何检查cpanel是否可以使用python2.7成功登录?
- laravel - 我的刀片未在模型视图中显示样式
- java - Sping Data返回空元素列表,但List有很多元素
- python - 为什么 pycharm 中的“in”运算符让我失望了?
- react-native - 在堆栈/屏幕之间传递参数