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做一个搜索引擎(Pylucene)的实例代码
Jul 05 Python
解决PyCharm中光标变粗的问题
Aug 05 Python
详解Python数据可视化编程 - 词云生成并保存(jieba+WordCloud)
Mar 26 Python
快速解决docker-py api版本不兼容的问题
Aug 30 Python
python进程池实现的多进程文件夹copy器完整示例
Nov 27 Python
如何使用Python破解ZIP或RAR压缩文件密码
Jan 09 Python
Tensorflow 多线程设置方式
Feb 06 Python
python爬虫开发之使用python爬虫库requests,urllib与今日头条搜索功能爬取搜索内容实例
Mar 10 Python
使用python编写一个语音朗读闹钟功能的示例代码
Jul 14 Python
python中的垃圾回收(GC)机制
Sep 21 Python
Python return语句如何实现结果返回调用
Oct 15 Python
Django如何继承AbstractUser扩展字段
Nov 27 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
php 特殊字符处理函数
2008/09/05 PHP
PHP PDOStatement::bindParam讲解
2019/01/30 PHP
使用composer 安装 laravel框架的方法图文详解
2019/08/02 PHP
Zero Clipboard js+swf实现的复制功能使用方法
2010/03/07 Javascript
jquery之empty()与remove()区别说明
2010/09/10 Javascript
js判断两个日期是否相等的方法
2013/09/10 Javascript
JQuery中层次选择器用法实例详解
2015/05/18 Javascript
js兼容火狐获取图片宽和高的方法
2015/05/21 Javascript
AngularJS删除路由中的#符号的方法
2016/09/20 Javascript
layui导航栏实现代码
2017/05/19 Javascript
Ionic2开发环境搭建教程
2020/08/20 Javascript
Vue.js常用指令之循环使用v-for指令教程
2017/06/27 Javascript
jQuery Ajax实现Select多级关联动态绑定数据的实例代码
2018/10/26 jQuery
Js 利用正则表达式和replace函数获取string中所有被匹配到的文本(推荐)
2018/10/28 Javascript
nodejs使用socket5进行代理请求的实现
2020/02/21 NodeJs
[03:17]2016完美“圣”典风云人物:冷冷专访
2016/12/08 DOTA
Python实现将xml导入至excel
2015/11/20 Python
python判断字符串编码的简单实现方法(使用chardet)
2016/07/01 Python
Python使用defaultdict读取文件各列的方法
2017/05/11 Python
Flask框架web开发之零基础入门
2018/12/10 Python
浅谈python之高阶函数和匿名函数
2019/03/21 Python
解决py2exe打包后,总是多显示一个DOS黑色窗口的问题
2019/06/21 Python
Selenium+Python 自动化操控登录界面实例(有简单验证码图片校验)
2019/06/28 Python
解决Django删除migrations文件夹中的文件后出现的异常问题
2019/08/31 Python
Django Admin中增加导出Excel功能过程解析
2019/09/04 Python
Python数据存储之 h5py详解
2019/12/26 Python
css3教程之倾斜页面
2014/01/27 HTML / CSS
幼儿园教师获奖感言
2014/03/11 职场文书
清扬洗发水广告词
2014/03/14 职场文书
《夹竹桃》教学反思
2014/04/20 职场文书
2014党委书记四风对照检查材料思想汇报
2014/09/21 职场文书
收费员岗位职责
2015/02/14 职场文书
酒店宣传语大全
2015/07/13 职场文书
SQLServer2008提示评估期已过解决方案
2021/04/12 SQL Server
Redis 哨兵机制及配置实现
2022/03/25 Redis
vue-cli3.0修改打包后的文件名和文件地址,打包后本地运行报错解决
2022/04/06 Vue.js