如何在Python库中解析数据包?

37
如何使用Python解析来自.pcap文件或接口的数据包?我特别寻求一个使用文档充分的库的解决方案。

嗨PSS,你完成了你的项目吗?你采用了哪种方法? - user2726660
1
为什么要关闭它,明显可以进行编辑呢? - jouell
对于更加更新的答案: 尝试使用 Kaitai Struct http://kaitai.io/,这是一个新兴的强大、快速的二进制解析器。 https://pythonistac.wordpress.com/2017/03/09/python-network-packet-dissection-frameworks-shootout-scapy-vs-construct-vs-hachoir-vs-kaitai-struct/ - PathToLife
4个回答

26

试一下scapy。它是一个非常强大的用于数据包检查、操纵和创建的程序。

你可以使用它构建自己的工具


请查看位于http://github.com/phaethon/scapy的新版本scapy。它与python3兼容,并包含新功能。 - Eriks Dobelis
8
请注意,scapy是遵循GPLv2许可的Python库之一,需要注意的是没有库例外。因此,如果您使用import scapy导入此库,您的代码也必须遵循GPLv2许可协议。如果您对此没有异议,请使用它。 - Hal

17
我尝试过那个,然后尝试了pcapy。我选择了pcapy,因为我的使用与我在Google上找到的示例类似。

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

11

我建议您使用Pyshark。这是对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>]
....

5

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接