如果字段名称是字符串变量,如何从数据包层获取字段值?

我有和作为变量。如何获取字段值?layerfield


#packet is just a sniff() packet


layer = "IP"

field = "src"


# I need something like

fieldValue = packet[layer].field


# or

fieldValue = packet[layer].getfieldval(field)



print("Layer: ", layer, " Field: ", field, " Value: ", fieldValue)

#Output- Layer: IP Field: src Value: 192.168.1.1


慕哥6287543
浏览 42回答 1
1回答

慕森卡

假设我们正在嗅探带有scapy的数据包,并希望查看其中的值。其中大部分是使用 scapy 文档来查找每个层具有的属性的问题。您也可以在python / scapy解释器中执行此操作,以查看它具有哪些属性和方法。例如:dir(packet)>>> dir(packet)... 'show', 'show2', 'show_indent', 'show_summary', 'sniffed_on', 'sprintf', 'src',...要从数据包中动态获取源属性,我们需要使用 getattr 函数,该函数可以从对象获取方法和属性。# Required if you are not using the scapy interpreterfrom scapy.all import sniff, IPlayer = "IP"field = "src"# Sniff 4 packets, filtering for packets with an IP layerpacket_list = sniff(filter="ip", count=4)# Choose first packet arbitrarilypacket0 = packet_list[0]# We can get the attribute reflexively because python allows itfield_value = getattr(packet0[layer], field)# Print this informationprint("Layer: ", layer, " Field: ", field, " Value: ", field_value)---> Layer:  IP  Field:  src  Value:  192.168.1.246
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python