python使用mitmproxy抓取浏览器请求的方法


Posted in Python onJuly 02, 2019

最近要写一款基于被动式的漏洞扫描器,因为被动式是将我们在浏览器浏览的时候所发出的请求进行捕获,然后交给扫描器进行处理,本来打算自己写这个代理的,但是因为考虑到需要抓取https,所以最后找到Mitmproxy这个程序。

安装方法:

pip install mitmproxy

接下来通过一个案例程序来了解它的使用,下面是目录结构

sproxy

|utils

|__init__.py

|parser.py

|sproxy.py

sproxy.py代码

#coding=utf-8
 
from pprint import pprint
from mitmproxy import flow, proxy, controller, options
from mitmproxy.proxy.server import ProxyServer
from utils.parser import ResponseParser
 
# http static resource file extension
static_ext = ['js', 'css', 'ico', 'jpg', 'png', 'gif', 'jpeg', 'bmp']
# media resource files type
media_types = ['image', 'video', 'audio']
 
# url filter
url_filter = ['baidu','360','qq.com']
 
static_files = [
 'text/css',
 'image/jpeg',
 'image/gif',
 'image/png',
]
 
class WYProxy(flow.FlowMaster):
 
 
 def __init__(self, opts, server, state):
  super(WYProxy, self).__init__(opts, server, state)
 
 def run(self):
  try:
   pprint("proxy started successfully...")
   flow.FlowMaster.run(self)
  except KeyboardInterrupt:
   pprint("Ctrl C - stopping proxy")
   self.shutdown()
 
 def get_extension(self, flow):
  if not flow.request.path_components:
   return ''
  else:
   end_path = flow.request.path_components[-1:][0]
   split_ext = end_path.split('.')
   if not split_ext or len(split_ext) == 1:
    return ''
   else:
    return split_ext[-1:][0][:32]
 
 def capture_pass(self, flow):
 	# filter url
  url = flow.request.url
  for i in url_filter:		
			if i in url:
				return True
 
  """if content_type is media_types or static_files, then pass captrue"""
  extension = self.get_extension(flow)
  if extension in static_ext:
   return True
 
  # can't catch the content_type
  content_type = flow.response.headers.get('Content-Type', '').split(';')[:1][0]
  if not content_type:
   return False
 
  if content_type in static_files:
   return True
 
  http_mime_type = content_type.split('/')[:1]
  if http_mime_type:
   return True if http_mime_type[0] in media_types else False
  else:
   return False
 
 @controller.handler
 def request(self, f):
 	pass
 
 @controller.handler
 def response(self, f):
  try:
   if not self.capture_pass(f):
    parser = ResponseParser(f)
    result = parser.parser_data()
    if f.request.method == "GET":
     print result['url']
    elif f.request.method == "POST":
     print result['request_content'] # POST提交的参数
 
  except Exception as e:
   raise e
 
 @controller.handler
 def error(self, f):
 	pass
  # print("error", f)
 
 @controller.handler
 def log(self, l):
 	pass
  # print("log", l.msg)
 
def start_server(proxy_port, proxy_mode):
 port = int(proxy_port) if proxy_port else 8090
 mode = proxy_mode if proxy_mode else 'regular'
 
 if proxy_mode == 'http':
  mode = 'regular'
 
 opts = options.Options(
  listen_port=port,
  mode=mode,
  cadir="~/.mitmproxy/",
  )
 config = proxy.ProxyConfig(opts)
 state = flow.State()
 server = ProxyServer(config)
 m = WYProxy(opts, server, state)
 m.run()
 
 
if __name__ == '__main__':
	start_server("8090", "http")

parser.py

# from __future__ import absolute_import
 
class ResponseParser(object):
 """docstring for ResponseParser"""
 
 def __init__(self, f):
  super(ResponseParser, self).__init__()
  self.flow = f
 
 def parser_data(self):
  result = dict()
  result['url'] = self.flow.request.url
  result['path'] = '/{}'.format('/'.join(self.flow.request.path_components))
  result['host'] = self.flow.request.host
  result['port'] = self.flow.request.port
  result['scheme'] = self.flow.request.scheme
  result['method'] = self.flow.request.method
  result['status_code'] = self.flow.response.status_code
  result['content_length'] = int(self.flow.response.headers.get('Content-Length', 0))
  result['request_header'] = self.parser_header(self.flow.request.headers)
  result['request_content'] = self.flow.request.content
  return result
 
 @staticmethod
 def parser_multipart(content):
  if isinstance(content, str):
   res = re.findall(r'name=\"(\w+)\"\r\n\r\n(\w+)', content)
   if res:
    return "&".join([k + '=' + v for k, v in res])
   else:
    return ""
  else:
   return ""
 
 @staticmethod
 def parser_header(header):
  headers = {}
  for key, value in header.items():
   headers[key] = value
  return headers
 
 @staticmethod
 def decode_response_text(content):
  for _ in ['UTF-8', 'GB2312', 'GBK', 'iso-8859-1', 'big5']:
   try:
    return content.decode(_)
   except:
    continue
  return content

参考链接:

https://github.com/ring04h/wyproxy

以上这篇python使用mitmproxy抓取浏览器请求的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
用Python创建声明性迷你语言的教程
Apr 13 Python
Python的string模块中的Template类字符串模板用法
Jun 27 Python
Python循环语句中else的用法总结
Sep 11 Python
python实现杨辉三角思路
Jul 14 Python
Python3.6 Schedule模块定时任务(实例讲解)
Nov 09 Python
使用Python设计一个代码统计工具
Apr 04 Python
Python中Numpy包的安装与使用方法简明教程
Jul 03 Python
Pycharm取消py脚本中SQL识别的方法
Nov 29 Python
Python使用pyshp库读取shapefile信息的方法
Dec 29 Python
Python lxml解析HTML并用xpath获取元素的方法
Jan 02 Python
详解从Django Rest Framework响应中删除空字段
Jan 11 Python
OpenCV python sklearn随机超参数搜索的实现
Jan 17 Python
Python使用线程来接收串口数据的示例
Jul 02 #Python
使用Python在Windows下获取USB PID&VID的方法
Jul 02 #Python
在windows下使用python进行串口通讯的方法
Jul 02 #Python
浅析Python 中几种字符串格式化方法及其比较
Jul 02 #Python
Python实用工具FuckIt.py介绍
Jul 02 #Python
Python如何实现转换URL详解
Jul 02 #Python
Pandas的read_csv函数参数分析详解
Jul 02 #Python
You might like
WML,Apache,和 PHP 的介绍
2006/10/09 PHP
基于jQuery的history历史记录插件
2010/12/11 Javascript
jQuery学习笔记之jQuery选择器的使用
2010/12/22 Javascript
了解了这些才能开始发挥jQuery的威力
2013/10/10 Javascript
IE8的JavaScript点击事件(onclick)不兼容的解决方法
2013/11/22 Javascript
基于JS实现html中placeholder属性提示文字效果示例
2018/04/19 Javascript
一个Vue视频媒体多段裁剪组件的实现示例
2018/08/09 Javascript
JavaScript实现表单注册、表单验证、运算符功能
2018/10/15 Javascript
Vue数据双向绑定的深入探究
2018/11/27 Javascript
在移动端使用vue-router和keep-alive的方法示例
2018/12/02 Javascript
浅谈一种让小程序支持JSX语法的新思路
2019/06/16 Javascript
vue+canvas实现拼图小游戏
2020/09/18 Javascript
[06:43]2018DOTA2国际邀请赛寻真——VGJ.Thunder
2018/08/11 DOTA
python批量提取word内信息
2015/08/09 Python
Python编程实现双击更新所有已安装python模块的方法
2017/06/05 Python
Python实战购物车项目的实现参考
2019/02/20 Python
Python爬虫之UserAgent的使用实例
2019/02/21 Python
Python3.5装饰器原理及应用实例详解
2019/04/30 Python
python读取并写入mat文件的方法
2019/07/12 Python
如何基于python操作json文件获取内容
2019/12/24 Python
查看keras的默认backend实现方式
2020/06/19 Python
CSS3中的常用选择器使用示例整理
2016/06/13 HTML / CSS
以实惠的价格轻松租车,免费取消:Easyrentcars
2019/07/16 全球购物
为什么说Ruby是一种真正的面向对象程序设计语言
2012/10/30 面试题
《北京的春节》教学反思
2014/04/07 职场文书
贺卡寄语大全
2014/04/11 职场文书
含预算的公司户外活动方案
2014/08/16 职场文书
创先争优活动党员公开承诺书
2014/08/29 职场文书
2014年师德师风工作总结
2014/11/25 职场文书
小学生差生评语
2014/12/29 职场文书
公司管理制度范本
2015/08/03 职场文书
营销策划分析:怎么策划才能更好销量产品?
2019/09/04 职场文书
导游词之无锡梅园
2019/11/28 职场文书
Windows 11要来了?微软文档揭示Win11太阳谷 / Win10有两个不同版本
2021/11/21 数码科技
MySQL读取JSON转换的方式
2022/03/18 MySQL
Python使用mitmproxy工具监控手机 下载手机小视频
2022/04/18 Python