2015-12-21 19 views
0

我正在使用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 

如何才能正確檢查某些圖層是否存在?

我當前的代碼是:提前

回答

1

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" 

對我的作品!

+0

謝謝偶氮的答案和幫助! –

相關問題