介绍
dpkt is a python module for fast, simple packet creation / parsing, with definitions for the basic TCP/IP protocols
dpkt 是一个解析快速简单的TCP/IP协议网络包的python 模块
安装
pip install dpkt
checkout the code
git clone https://github.com/kbandla/dpkt.git
实例
打印packets 实例
This example uses DPKT to read in a pcap file and print out the contents of the packets This example is focused on the fields in the Ethernet Frame and IP packet
打印时间戳 UTC
import datetime
import dpkt
import pcapng
with open("filename",'rb') as fp:
pcapng=dpkt.pcapng.Reader(fp)
for timestamp,buf in pcapng:
print('Timestamp:',str(datetime.datetime.utcfromtimestamp(timestamp)))
输出
Timestamp: 2023-09-06 11:17:45.750188
打印Ethernet Frame 数据链路层信息
with open("filename",'rb') as fp:
pcapng=dpkt.pcap.Reader(fp)
for timestamp,buf in pcapng:
eth = dpkt.ethernet.Ethernet(buf)
ip=eth.data
tcp=ip.data
print('Timestamp:',str(datetime.datetime.utcfromtimestamp(timestamp)))
print("Ethernet Frame:",eth.src,eth.dst,eth.type)
print('source port;',tcp.sport)
print('dst port',tcp.dport)
print('ip len',ip.len)
输出(默认输出为)
Timestamp: 2023-09-06 11:17:45.750188
Ethernet Frame: b'\x02G\x00\x00\x000' b'\x02G\x00\x00\x00\x0e' 2048
source port; 30501
dst port 30501
ip len 1094
打印packet_data 信息
包的第一个block为SectionHeader 信息(cpu, os, wireshark version等);
包的第二个block为InterfaceDescription, 主要是接口的信息, 如以太网网卡信息等
包的第三个block以及往后才开始是EnhancedPacket,若不用打印上述信息,则可以通过计数,从第三个开始打印。
with open("filename",'rb') as fp:
scanner = pcapng.FileScanner(fp)
cnt = -2
for block in scanner:
cnt += 1
if cnt > 0:
playload=block.packet_data
# 将二进制数据转换为十六进制字符串
hex_data = binascii.b2a_hex(playload).decode()
# 将十六进制字符串转换为字符串
str_data = hex_data.replace('\\x', '')
print(str_data)
输出(实例)
输出的内容如下:
02470000000e024700000030080