读pcap大文件,过滤指定IP的报文

#应用此脚本需要了解pcap文件的格式,请查看博客中的其他专项介绍

#coding=utf-8
import os
import socket
import struct
import os,time,threading
import subprocess

class pcap():
def init(self, file,ip,size_file):
self.ip=ip
self.size_file=size_file
#print(self.ip)
self.file = file
self.i=self.file.split(‘/’)[-1].split(‘.’)[0]# 取路径中的文件名
self.file_pcap=open(‘D:/python/pcap1/target.pcap’,‘ab+’)
def db_log(self):

    f=open(self.file,'rb')
    #print(f.seek(200))
    #print(f.read(2))
    pcap_file = f.read(40)  
    if count==0:
        pcap_file_header=pcap_file[0:24]
        self.file_pcap.write(pcap_file_header)
    #print(srcbytearr.find(magic_number,0))
    #print(srcbytearr)
    #print(srcbytearr[0:36])
    #print(srcbytearr[16:20])
    #packet_len=struct.unpack('I',pcap_file[32:36])[0]
    #print(srcbytearr[36:40])

    #startindex=0
    j=24
    len1=24
    len2=0
    #print(len(pcap_file))
    while (j<self.size_file):
        f.seek(j+8) #获取报文的抓包长度,而不是报文长度,有些软件抓包会自动截短报文
        #packet_len=struct.unpack('I',pcap_file[j+8:j+12])[0]
        packet_len=struct.unpack('I',f.read(4))[0]
        #print(packet_len)
        len2=len1+16+packet_len
        #print(len1)
        #print(len2)
        f.seek(len1)
        s=f.read(len2-len1)
        srcip=struct.unpack('I',s[42:46])[0]
        dstip=struct.unpack('I',s[46:50])[0]
        #print(srcip)
        #print(dstip)
        #srcport=str(struct.unpack('>H',s[50:52])[0])
        #dstport=str(struct.unpack('>H',s[52:54])[0])
        #print(srcport)
        srcip=socket.inet_ntoa(struct.pack("!I",socket.htonl(srcip)))
        dstip=socket.inet_ntoa(struct.pack("!I",socket.htonl(dstip)))
        #!表示我们要使用网络字节顺序解析,因为我们的数据是从网络中接收到的,在网络上传送的时候它是网络字节顺序的:大端
        #主机字节序:小端
        #print(srcip)
        #print(dstip)
       #print(srcport1)
        #print(srcport)

        #print(s.hex())
        
        if self.ip==srcip or self.ip==dstip:
                #print('111111111111111111')
                self.file_pcap.write(s)
                len1=len2
                j=len2   
        else: 
                #print('000000000000000')
                               
                len1=len2
                j=len2
                #print(----len2)
    f.close()    

if name == ‘main’:

ip="222.222.123.184"
count=0
for fpathe,dirs,fs in   os.walk('D:/converted'):#路径可修改
    for fl in fs:
        print(fl)
        size_file=os.path.getsize(os.path.join(fpathe,fl))
        #print(size_file)
        s=pcap(os.path.join(fpathe,fl),ip,size_file)
        s.db_log()    
        count=count+1
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值