如何在Python库中解析数据包?
如何用Python从.pcap文件或网络接口中解析数据包?
我特别想找一个使用文档齐全的库的解决方案。
4 个回答
10
我推荐你使用Pyshark。它是tshark的一个封装工具,也就是说它可以让你更方便地使用tshark的功能。它支持所有tshark的过滤器、解码库等等,而且使用起来很简单!
这个工具非常适合解析.pcap文件,也可以进行实时捕获数据。
https://pypi.python.org/pypi/pyshark
示例代码(来自链接):
import pyshark
cap = pyshark.FileCapture('/root/log.cap')
cap
>>> <FileCapture /root/log.cap>
print cap[0]
Packet (Length: 698)
Layer ETH:
Destination: BLANKED
Source: BLANKED
Type: IP (0x0800)
Layer IP:
Version: 4
Header Length: 20 bytes
Differentiated Services Field: 0x00 (DSCP 0x00: Default; ECN: 0x00: Not-ECT (Not ECN-Capable Transport))
Total Length: 684s
Identification: 0x254f (9551)
Flags: 0x00
Fragment offset: 0
Time to live: 1
Protocol: UDP (17)
Header checksum: 0xe148 [correct]
Source: BLANKED
Destination: BLANKED
...
dir(cap[0])
['__class__', '__contains__', '__delattr__', '__dict__', '__dir__', '__doc__', '__format__', '__getattr__', '__getattribute__', '__getitem__', '__getstate__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_packet_string', 'bssgp', 'captured_length', 'eth', 'frame_info', 'gprs-ns', 'highest_layer', 'interface_captured', 'ip', 'layers', 'length', 'number', 'pretty_print', 'sniff_time', 'sniff_timestamp', 'transport_layer', 'udp']
cap[0].layers
[<ETH Layer>, <IP Layer>, <UDP Layer>, <GPRS-NS Layer>, <BSSGP Layer>]
....
17
我试过那个方法,然后又试了pcapy。我选择pcapy是因为我的使用场景和我在网上找到的一个例子很相似。
http://snipplr.com/view/3579/live-packet-capture-in-python-with-pcapy/(或者你可以看看下面复制的相同代码)
import pcapy
from impacket.ImpactDecoder import *
# list all the network devices
pcapy.findalldevs()
max_bytes = 1024
promiscuous = False
read_timeout = 100 # in milliseconds
pc = pcapy.open_live("name of network device to capture from", max_bytes,
promiscuous, read_timeout)
pc.setfilter('tcp')
# callback for received packets
def recv_pkts(hdr, data):
packet = EthDecoder().decode(data)
print packet
packet_limit = -1 # infinite
pc.loop(packet_limit, recv_pkts) # capture packets