如果字段名称是字符串变量,如何从数据包层获取字段值?
How to get a field value from a packet layer if the field name is a string variable?
我有 layer
和 field
作为变量。如何获取字段值?
#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
假设我们正在用 scapy 嗅探数据包,想看看里面的值。其中大部分是使用 scapy documentation 查找每个层具有的属性的问题。您也可以在 python/scapy 解释器中使用 dir(packet)
执行此操作,以查看它具有哪些属性和方法。例如:
>>> dir(packet)
...
'show',
'show2',
'show_indent',
'show_summary',
'sniffed_on',
'sprintf',
'src',
...
要从数据包中动态获取源属性,我们需要使用getattr function,它可以从对象中获取方法和属性。
# Required if you are not using the scapy interpreter
from scapy.all import sniff, IP
layer = "IP"
field = "src"
# Sniff 4 packets, filtering for packets with an IP layer
packet_list = sniff(filter="ip", count=4)
# Choose first packet arbitrarily
packet0 = packet_list[0]
# We can get the attribute reflexively because python allows it
field_value = getattr(packet0[layer], field)
# Print this information
print("Layer: ", layer, " Field: ", field, " Value: ", field_value)
---
> Layer: IP Field: src Value: 192.168.1.246
我有 layer
和 field
作为变量。如何获取字段值?
#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
假设我们正在用 scapy 嗅探数据包,想看看里面的值。其中大部分是使用 scapy documentation 查找每个层具有的属性的问题。您也可以在 python/scapy 解释器中使用 dir(packet)
执行此操作,以查看它具有哪些属性和方法。例如:
>>> dir(packet)
...
'show',
'show2',
'show_indent',
'show_summary',
'sniffed_on',
'sprintf',
'src',
...
要从数据包中动态获取源属性,我们需要使用getattr function,它可以从对象中获取方法和属性。
# Required if you are not using the scapy interpreter
from scapy.all import sniff, IP
layer = "IP"
field = "src"
# Sniff 4 packets, filtering for packets with an IP layer
packet_list = sniff(filter="ip", count=4)
# Choose first packet arbitrarily
packet0 = packet_list[0]
# We can get the attribute reflexively because python allows it
field_value = getattr(packet0[layer], field)
# Print this information
print("Layer: ", layer, " Field: ", field, " Value: ", field_value)
---
> Layer: IP Field: src Value: 192.168.1.246