Skip to main content
 首页 » 编程设计

python之如何使用 scapy 创建新层或新协议(protocol)

2024年10月01日8fff_TT

我想使用 scapy 创建一个新层。我创建了一个新图层,但是当我将它发送到另一台计算机时它丢失了,Wireshark 也无法识别它。我该如何解决这个问题?

class OMER(Packet): 
    name = "OMER" 
    fields_desc = [StrLenField("Omer", "", None)] 

请您参考如下方法:

当您使用 scapy 创建新协议(protocol)或新层时,其他网络工具,如 wireshark (和其他人)因为他们不知道您的协议(protocol)的细节将无法正确地自动解析它。

如果你想尝试一个新的协议(protocol),你将不得不创建你自己的本地解码器。以下示例即使是最小的示例,也演示了上述所有内容:


#!/usr/bin/env python  
 
from scapy.all import * 
 
# create a simple protocol  
# (example similar with the one in the scapy docs...) 
class Exmpl(Packet): 
    name = "myprotocol" 
    fields_desc=[ ShortField("fld1",5), 
                  XByteField("fld2",3) ] 
 
from scapy.utils import PcapWriter 
 
# write data in a pcap file to examine later with 
# 1 -> scapy 
# 2 -> wireshark 
print '\n[+] Writing net.pcap file...' 
cap = PcapWriter("net.pcap", append=True, sync=True) 
for i in range(10): 
    packet = Exmpl(fld1=i) 
    cap.write(packet) 
 
# read the data and examine them with scapy 
# scapy is aware of the "Exmpl" protocol (e.g. its fields etc...)  
# and how to decode it, while wireshark is not 
print '[+] Examining net.pcap file...\n' 
packets = rdpcap('net.pcap') 
for p in packets:  
    Exmpl(str(p)).show() 

以上脚本的输出如下:

[+] Writing net.pcap file... 
[+] Examining net.pcap file... 
 
###[ myprotocol ]### 
  fld1      = 0 
  fld2      = 0x3 
###[ myprotocol ]### 
  fld1      = 1 
  fld2      = 0x3 
###[ myprotocol ]### 
  fld1      = 2 
  fld2      = 0x3 
...skip... 

如你所见知道协议(protocol),因此可以正确解析数据。现在,如果您尝试使用 wireshark 检查“net.pcap”文件,您将看到以下内容:

不知道您的协议(protocol),因此它无法正确解析它。

注意:如您所知,即使您在另一台设备中发送这些数据包(要真正做到这一点,您还必须实现其他一些东西)那么该设备也必须知道你的协议(protocol),否则它将无法正确解析它。这就是为什么当您尝试将数据包从一台计算机发送到另一台计算机时,接收方无法成功解码的原因。