python Grab Package Save as pcap File and Parse Instance
- 2021-07-24 11:28:53
- OfStack
The first is to grab packets and use scapy module.
The sniff () function opens the local file when the argument is the local file path
If the parameters are BPF filtering rule and callback function, Sniff is performed, and the callback function is used to process the data packet from Sniff
import os
from scapy.all import *
pkts=[]
count=0
pcapnum=0
filename=''
def test_dump_file(dump_file):
print "Testing the dump file..."
if os.path.exists(dump_file):
print "dump fie %s found." %dump_file
pkts=sniff(offline=dump_file)
count = 0
while (count<=2):
print "----Dumping pkt:%s----" %dump_file
print hexdump(pkts[count])
count +=1
else:
print "dump fie %s not found." %dump_file
def write_cap(x):
global pkts
global count
global pcapnum
global filename
pkts.append(x)
count +=1
if count ==3: <span style="font-family: Arial, Helvetica, sans-serif;"># Every 3 A TCP Operation seal as 1 Packs (use as many as possible to check correctness) </span>
pcapnum +=1
pname="pcap%d.pcap"%pcapnum
wrpcap(pname,pkts)
filename ="./pcap%d.pcap"%pcapnum
test_dump_file(filename)
pkts=[]
count=0
if __name__=='__main__':
print "Start packet capturing and dumping ..."
sniff(filter="dst net 127.0.0.1 and tcp",prn=write_cap) #BPF Filtering rule
The following is the parsing of pcap file, which will automatically find the next pcap file and divide it according to src. ip and dst. ip
# -*- coding: cp936 -*-
import re
import zlib
import os
from scapy.all import *
num=1
a=rdpcap("pcap1.pcap") # Loop to open a file
while True:
try:
num+=1
file_name="pcap%d.pcap" % num
b=rdpcap(file_name)
a=a+b
except:
break
print "[*] Read pcap file ok"
print "[*] Begin to parse pcapfile..."
print a
try:
#print "[*] OPen new pcap_file %s" % pcap_file
sessions=a.sessions()
for session in sessions:
print "[*]New session %s" % session
data_payload=""
for packet in sessions[session]:
try:
data_payload +=str(packet[TCP].payload)
print "[**] Data:%s" % data_payload
except:
pass
except:
print "[*]no pcapfile..."