[英]How to Calculate Captured Packet(s) Size using scapy
Recently I started to code using Scapy. 最近,我开始使用Scapy进行编码。 Basing on the example from: 基于以下示例:
Scapy Sniffing with Custom Actions Scapy嗅探与自定义动作
I capture multicast UDP datagrams, but besides the amount of captured packets per second, I would like to store the size(in bytes) of packets captured each second(by that I'd multiply the result by 8 and I'd have bitrate). 我捕获了多播UDP数据报,但是除了每秒捕获的数据包数量之外,我还想存储每秒捕获的数据包的大小(以字节为单位)(将结果乘以8,然后得到比特率) 。 The problem is that capturedPacketsSize
seems to be undefined nevertheless I defined it before def custom_action()
. 问题是, capturedPacketsSize
似乎是未定义的,但是我在def custom_action()
之前定义了它。
I tried to define capturedPacketsSize
in different places for eg before sniffing in while 1
loop. 我试图在不同的地方定义capturedPacketsSize
,例如在监听while 1
循环之前。 The same result. 相同的结果。
from collections import Counter
from scapy.all import sniff
packet_counts = Counter()
capturedPacketsSize = 0
## Define our Custom Action function
def custom_action(packet):
# Create tuple of Src/Dst in sorted order
capturedPacketsSize += len(packet) #here occurs error
key = tuple(sorted([packet[0][1].src, packet[0][1].dst]))
packet_counts.update([key])
#return "Packet #{0}: {1} ==> {2}".format(sum(packet_counts.values()), packet[0][1].src, packet[0][1].dst)
print("_____.:|Entering infinite while loop|:._____")
while 1:
print("Analysing Multicast packets")
pkt = sniff(iface="eno4", filter="udp", prn=custom_action, timeout=1)
print("\n".join("{0} <--> {1} :{2}".format(key[0], key[1], count) for key, count in packet_counts.items()))
packet_counts.clear()
print("Byterate for this moment is equal to: {0} Bytes per second".format(capturedPacketsSize))
Use the global
keyword for the variable names inside the function- 使用global
关键字为函数中的变量名-
def custom_action(packet):
global capturedPacketsSize
global packet_counts
# Create tuple of Src/Dst in sorted order
capturedPacketsSize += len(packet) #here occurs error
key = tuple(sorted([packet[0][1].src, packet[0][1].dst]))
packet_counts.update([key])
You can read more about this keyword here 您可以在此处了解有关此关键字的更多信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.