检查对象是否在pyshark给出的列表中

时间:2015-12-23 18:04:58

标签: python list object

我正在尝试使用pyshark读取pcap文件。似乎pyshark创建了一个对象列表,其中每个对象 有关于数据包内每层的信息。

我只想评估数据包中是否存在图层。也许有人可以帮助我。

对象列表“layers”是这样的:

[<ETH Layer>, <IP Layer>, <SCTP Layer>, <DATA Layer>]

但是这个评估失败了,因为列表中的内容是对象而不是字符串。

if <ETH Layer> in layers: print "Yes, Ethernet layer exists"
if '<ETH Layer>' in layers: print "Yes, Ethernet layer exists"

以下是我的测试...

Python 2.7.10 (default, May 23 2015, 09:40:32) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> import pyshark
>>> file = pyshark.FileCapture('C:\\files\\input.pcap')
>>> packet=file[0]
>>> layers=packet.layers
>>> layers
[<ETH Layer>, <IP Layer>, <SCTP Layer>, <DATA Layer>, <SCTP Layer>, <DATA Layer>]
>>> if packet.eth in layers: print "Yes, Ethernet layer exists"
...
Yes, Ethernet layer exists
>>>
Yes, Ethernet layer exists
>>> if '<ETH Layer>' in layers: print "Yes, Ethernet layer exists"
...
>>>

此评估提供正确的输出

if packet.eth in layers: print "Yes, Ethernet layer exists"

这两个失败,因为评估为假

if <ETH Layer> in layers: print "Yes, Ethernet layer exists"
if '<ETH Layer>' in layers: print "Yes, Ethernet layer exists"

*更新:

如果我测试packet.ip,packet.eth,packet.sctp它只在层ip,eth或sctp存在的情况下工作,如果某个层不存在(即tcp)我得到下面的错误。

>>> if packet.tcp in layers: print "Yes, Ethernet layer exists"
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\site-packages\pyshark\packet\packet.py", line 110, in __getattr__
    raise AttributeError()
AttributeError

由于

1 个答案:

答案 0 :(得分:2)

<ETH Layer>不是实际对象,而是对象的__repr__方法返回的内容。您的Python REPL调用它来查看如何打印出已计算表达式的表示。同样,如果您要求__str__表达式,它可能会调用print。比较这些:

>> packet.layers[0]
<ETH Layer>

>> print packet.layers[0]
Layer ETH:
    Destination: 52:54:00:12:37:02 (52:54:00:12:37:02)
    .... ..1. .... .... .... .... = LG bit: Locally administered address (this is NOT the factory default)
    Address: 52:54:00:12:37:02 (52:54:00:12:37:02)
    .... ...0 .... .... .... .... = IG bit: Individual address (unicast)
    Type: IP (0x0800)
    Source: 08:00:28:1d:ae:8b (08:00:28:1d:ae:8b)
    .... ..0. .... .... .... .... = LG bit: Globally unique address (factory default)
    Address: 08:00:28:1d:ae:8b (08:00:28:1d:ae:8b)
    .... ...0 .... .... .... .... = IG bit: Individual address (unicast)

但是为了在功能上回答你的问题,我相信如果你想看看你的数据包中是否存在一个层,你可以做类似的事情:

if 'eth' in packet:
    # ...