检查pyshark中的当前数据包中是否存在图层-python
问题描述:
我正在使用pyshark读取pcap文件,并且想要打印每个数据包中包含的每个图层的一些字段。检查pyshark中的当前数据包中是否存在图层-python
我把一个if条件来检查当前数据包中是否存在特定图层,如果为True,则打印一些字段。
当pkt.layers中存在图层时,条件起作用,但当 图层不存在时,我得到“raise AttributeError()”,在我的情况下tcp图层不存在于第一个包中然后我得到错误和脚本停止。
pkt.layers的内容具有这种格式
[<ETH Layer>, <IP Layer>, <TCP Layer>]
,它似乎是一个列表,但如果我尝试是否有这些字符串存在的结果如下评价始终为false。
>>> layers = pkt.layers
>>> layers
[<ETH Layer>, <IP Layer>, <TCP Layer>]
>>> "<ETH Layer>" in layers
False
如何才能正确检查某些图层是否存在?
我当前的代码是:提前
答
import pyshark
# Open saved trace file
cap = pyshark.FileCapture('file.pcap')
for pkt in cap:
lyr = pkt.layers # Current layers
if p.eth in lyrs: print p.eth.src # If Ethernet layer exists print ethernet value
if p.ip in lyrs: print p.ip.src # If IP layer exists print source IP
if p.tcp in lyrs: print p.tcp.port # If TCP layer exists print port
感谢试试这个:
if("protocol" in str(p.layers):
doSomething()
例子:
if("TCP" in str(p.layers)):
print "tcp found"
对我的作品!
谢谢偶氮的答案和帮助! –