2014-12-03 45 views
7

使用python數據包解析/嗅探工具Scapy,我想從原始字節串創建一個數據包。雖然我的具體使用情況的細節更加真實,下面的例子說明我的問題,我現在的嘗試:如何從原始字節創建Scapy數據包

# Get an example packet (we won't really have an offline file in production.) 
pkt = sniff(offline="./example_packets/example_packets2.pcap") 

# Convert it to raw bytes -- oddly __str__ does this. 
raw_packet = str(pkt) 

# Current, broken, attempt to construct a new packet from the same bytes as the old. 
# In truth, there are easier ways to copy packets from existing Scapy packets, but 
# we are really just using that offline packet as a convenient example. 
new_packet = Packet(_pkt=raw_packet) 

# Sadly, while this packet has the bytes internally, it no longer has the 
# interpretations of the layers like the original packet did (such as saying that 
# the packet is ARP and has these field values, etc. 
print repr(new_packet) 

我怎麼能生產出從上看起來一樣的原始字節的new_packet就好像聞從一個pcap文件?

回答

7

Scapy無法猜測數據包的第一層,因此您需要指定它。

您可以使用相應的Packet子類來實現。例如,假設您的數據包的第一層是以太網,請使用Ether(raw_packet)而不是Packet(raw_packet)

+1

如果使用'Ether'類,Scapy能夠自動確定其他圖層嗎?似乎「嗅探」功能不知何故會發現其他層。 – BlackVegetable 2014-12-03 13:58:53

+1

如果其他層指的是以太網層的頂層,答案是肯定的,這要歸功於'type'字段。 – Pierre 2014-12-03 14:01:11

+0

當然!這應該對我來說很明顯。感謝您的澄清。 (如果路由器不知道類型信息,路由器怎麼知道如何解釋其他層?) – BlackVegetable 2014-12-03 14:06:47