在尝试从解析的pcap中添加变量时,我得到了一个关键错误。
在这里,我试图得到最后一个时间戳,但是我得到了一个关键错误
KeyError: 'UPD'
lst_timestamp = {}
for ts, buf in packets:
eth = dpkt.ethernet.Ethernet(buf)
ip = eth.data
protocol_number = ip.p
traffic_type = protocoltype.proto[protocol_number]
if traffic_type not in traffic_types:
traffic_types.append(traffic_type)
if traffic_type in no_packets: # check the key is in the dictionary
no_packets[traffic_type] += 1
else:
no_packets[traffic_type] = 1
if traffic_type not in fst_timestamp:
fst_timestamp[traffic_type] = ts
if traffic_type in lst_timestamp:
lst_timestamp[traffic_type] = ts错误发生在这里:
if traffic_type in lst_timestamp:
lst_timestamp[traffic_type] = ts我对python相当陌生,所以我试图找出这个错误发生的原因,但是我搞不懂,任何帮助都是非常有意义的。
全部密码。
import dpkt
import socket
from tabulate import tabulate
import protocoltype
def main() -> list:
"""parse pcap"""
pcap_file = "evidence-packet-analysis.pcap"
packets = []
open_file = open(pcap_file, "rb")
for ts, buf in dpkt.pcap.Reader(open_file):
packets.append((ts, buf))
open_file.close()
print(f"'{pcap_file}' Successfully Read")
table(packets)
def table(packets):
traffic_types = []
no_packets = {}
fst_timestamp = {}
lst_timestamp = {}
for ts, buf in packets:
eth = dpkt.ethernet.Ethernet(buf)
ip = eth.data
protocol_number = ip.p
traffic_type = protocoltype.proto[protocol_number]
if traffic_type not in traffic_types:
traffic_types.append(traffic_type)
if traffic_type in no_packets: # check the key is in
the dictionary
no_packets[traffic_type] += 1
else:
no_packets[traffic_type] = 1
if traffic_type not in fst_timestamp:
fst_timestamp[traffic_type] = ts
if traffic_type in lst_timestamp:
lst_timestamp[traffic_type] = ts
rows = []
for traffic_type in traffic_types:
rows.append([traffic_type, no_packets[traffic_type],
fst_timestamp[traffic_type], lst_timestamp[traffic_type], 0])
print(tabulate(
rows,
headers=["traffic_type", "no_packets", "fst_timestamp",
"lst_timestamp", "mean_packet_length"]
))
if __name__ == "__main__" :
main()模块协议类型只是一个字典,将协议号与协议类型联系起来。
发布于 2021-12-17 18:52:45
错误不在此:
if traffic_type in lst_timestamp:
lst_timestamp[traffic_type] = ts只是因为你添加了这段代码。但发生这种情况的主要原因是:
rows.append([traffic_type, no_packets[traffic_type],
fst_timestamp[traffic_type], lst_timestamp[traffic_type], 0])让我解释一下:
假设在列表traffic_type中有一个用于traffic_types的'UDP‘键
然后:
如果traffic_type不在no_packets或fst_timestamp中,则需要插入它。
if traffic_type in no_packets: # check the key is in
the dictionary
no_packets[traffic_type] += 1
else:
no_packets[traffic_type] = 1
if traffic_type not in fst_timestamp:
fst_timestamp[traffic_type] = ts但是,如果键traffic_type不在lst_timestamp中,那么您就没有插入它,如果它已经存在,您只是在递增。
我假设关键的traffic_type。‘'UDP’不是lst_timestamp,所以代码中没有关于它的任何内容。
但接下来是这句话:
rows.append([traffic_type, no_packets[traffic_type],
fst_timestamp[traffic_type], lst_timestamp[traffic_type], 0])这里您正在访问lst_timestamp[traffic_type],即不在列表中的lst_timestamp['UPD']。
因此,在添加字典时,您将得到KeyError:'UPD'。
如有任何疑问,请随时发表评论。
https://stackoverflow.com/questions/70396186
复制相似问题