PyShark入门(3):capture对象

原文链接:http://zodiacg.net/2016/07/in...

本系列文章译自thePacketGeek的系列文章。原创翻译,转载请注明出处。

我们已经了解了如何使用 FileCaptureLiveCapture 模块来捕获数据包,下面我们来看一下如何使用返回的 capture 对象。

dir(cap)
Out[3]:
['apply_on_packets',
 'close',
 'current_packet',
 'display_filter',
 'encryption',
 'input_filename',
 'next',
 'next_packet']

(简洁起见以上列表经过了精简)

这些是我认为比较有用的方法和属性,其它大多数是用于调试或者捕获过程内部使用。 display_filterencryptioninput_filename 属性是之前传递给 FileCapture 或者 LiveCapture 的值。

此处真正强大的是apply_on_packets()next()方法。next()方法使得 capture 对象可以通过for循环进行遍历。
apply_on_packets() 方法是另一种遍历数据包的方式,它接受一个函数作为参数并将之作用于所有的数据包。

>>> cap = pyshark.FileCapture('test.pcap', keep_packets=False)
>>> def print_highest_layer(pkt)
...: print pkt.highest_layer
>>> cap.apply_on_packets(print_highest_layer)
HTTP
HTTP
HTTP
HTTP
HTTP
... (truncated)

这个方法也可以用于打印之外的功能,例如将数据包添加入一个列表进行其它处理。下面的脚本会将所有的数据包加入到一个列表中并打印总数:

import pyshark

def get_capture_count():
    p = pyshark.FileCapture('test.cap.pcap', keep_packets=False)

    count = []
    def counter(*args):
        count.append(args[0])

    p.apply_on_packets(counter, timeout=100000)

    return len(count)

print get_capture_count()

上一篇:PyShark入门(2):FileCapture和LiveCapture模块
下一篇:PyShark入门(4):capture对象

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值