原文连接:http://zodiacg.net/2016/07/in...python
本系列文章译自thePacketGeek的系列文章。原创翻译,转载请注明出处。app
咱们已经了解了如何使用 FileCapture 和 LiveCapture 模块来捕获数据包,下面咱们来看一下如何使用返回的 capture 对象。函数
dir(cap) Out[3]: ['apply_on_packets', 'close', 'current_packet', 'display_filter', 'encryption', 'input_filename', 'next', 'next_packet']
(简洁起见以上列表通过了精简).net
这些是我认为比较有用的方法和属性,其它大多数是用于调试或者捕获过程内部使用。 display_filter , encryption 和 input_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)
这个方法也能够用于打印以外的功能,例如将数据包添加入一个列表进行其它处理。下面的脚本会将全部的数据包加入到一个列表中并打印总数:code
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对象对象