Scapy is easy to operate with Pcap files in a Linux environment, but under Windows, In particular, in the python2.7 environment will encounter a variety of dependency packages can not be used, the most obvious may belong to Dnet and Pcap Python dependency package, because Scapy Conf.use_pcap and Conf.use_ Dnet cannot be configured in a Windows environment and is forcibly set to 1 in scapy\arch\windows\__init__.py, that is, pcap and dnet dependent packages must be used. The specific code is shown below
fromScapy.sendrecvImportDebug, SRP1 fromScapy.layers.l2Importether, ARP fromScapy.dataImportMTU, Ether_broadcast, Eth_p_arpconf.use_pcap= 1conf.use_dnet= 1 fromScapy.archImportpcapdnet fromScapy.arch.pcapdnetImport*Loopback_name="Lo0"WINDOWS= True
Google once again, the basic is in the environment of windos+python2.6 use scapy, very few use windows+python2.7, after many setbacks, and Cygwin is MinGW finally fix dnet and pcap in windows+ python2.7 's bag.
The specific:
Pcap Http://files.cnblogs.com/Jerryshome/pcap-1.1.win32-py2.7.rar
Dnet Http://files.cnblogs.com/Jerryshome/dnet-1.12.win32-py2.7.rar
The following code shows how to use Scapy to complete pcap reading and writing, and provides a picklablepacket class for solving the problem of scapy parsing packet cannot be serialized, the code is as follows:
Importscapy fromScapy.allImport* fromScapy.utilsImportPcapreader, PcapwriterImportGzip,zlib,cpickleclassPicklablepacket:" "A container for scapy packets so can be pickled (in contrast to scapy pakcets themselves)" " def __init__(self, PKT): Self.contents=Str (PKT) Self.time=Pkt.timedef __call__(self):" "Get the original scapy packet" "PKT=Scapy.layers.l2.Ether (self.contents) pkt.time=Self.timereturnPKTdefdumps (self):" "Use cpickle to dump" " returnGzip.zlib.compress (Cpickle.dumps (self)). Encode ('Base64') @staticmethoddefloads (string):" "load object from string" "P= Cpickle.loads (Gzip.zlib.decompress (String.decode ('Base64'))) returnp ()defRead (file_name, start, count):" "read packets from Pcap according to the start packet number and total count" "Reader=Pcapreader (file_name)ifStart >0:reader.read_all (start)ifCount >0:returnReader.read_all (count)Else: returnReader.read_all (-1)defWrite (file_name, packets): Writer= Pcapwriter (file_name, append =True) forPinchPackets:writer.write (P) Writer.flush () writer.close ()if __name__=='__main__': Packets= Read ('726445cd34b7273ebea2973bbd6e784c. C39bc427.pcap', 0, 10) #Packle the packets to transferp =Picklablepacket (packets[0]) s=p.dumps () p=Picklablepacket.loads (s)PrintPPrintp.summary () serialized_packets= [Picklablepacket (P). Dumps () forPinchPackets] Deserialized_packets= [Picklablepacket.loads (s) forSinchSerialized_packets] Write ('New.pcap', packets)
Read and write to pcap files using scapy+python2.7 under Windows