欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

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

时间:2021-10-22 09:08:53|栏目:Python代码|点击:

首先是抓包,使用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:             <span style="font-family: Arial, Helvetica, sans-serif;">#每3个TCP操作封为一个包(为了检测正确性,使用时尽量增多)</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过滤规则

下面是对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..."

上一篇:Pandas 连接合并函数merge()详解

栏    目:Python代码

下一篇:Python读取图片EXIF信息类库介绍和使用实例

本文标题:python 抓包保存为pcap文件并解析的实例

本文地址:http://www.codeinn.net/misctech/180873.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有