python 抓包保存为pcap文件并解析

首先是抓包,使用scapy模块,


sniff()函数 在其中参数为本地文件路径时,操作为打开本地文件

若参数为BPF过滤规则和回调函数,则进行Sniff,回调函数用于对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:                         #每3个TCP操作封为一个包(为了检测正确性,使用时尽量增多)

			
			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过滤规则
   
        



下面是对pcap文件的解析,会自动查找下一个pcap文件,按照src.ip和dst.ip进行划分



# -*- coding: cp936 -*-
import re
import zlib
import os

from scapy.all import *
num=1
a=rdpcap("pcap1.pcap")                             #循环打开文件
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..."

       

你可能感兴趣的:(通信)