python+mitmproxy抓包的實現(xiàn)
什么是mitmproxy
Mitmproxy 就是用于 MITM 的 Proxy,MITM 即中間人攻擊(Man-in-the-middle attack)。不同于 fiddler ,charles或 wireshark 等抓包工具,mitmproxy 不僅可以抓取請求響應(yīng)幫助開發(fā)者查看、分析,更可以通過自定義python腳本進(jìn)行二次開發(fā)。
安裝
pip安裝
pip install mitmproxy # 驗證 mitmproxy --version
安裝證書
打開系統(tǒng)代理,將系統(tǒng)代理設(shè)置為127.0.0.1:8080(mitmproxy默認(rèn)代理)或192.168.xxx.xxx:8080(本機ip,用于局域網(wǎng))
cmd輸入mitmproxy, 瀏覽器訪問 http://mitm.it/,下載證書安裝。
代碼安裝(自動化)
設(shè)置系統(tǒng)代理(win)
import ctypes
import winreg
def set_proxy(enable_proxy, proxy_address="http://127.0.0.1:8080"):
try:
# 代理服務(wù)器地址和端口
proxy_server = proxy_address
# 打開注冊表鍵
key_path = r"Software\Microsoft\Windows\CurrentVersion\Internet Settings"
key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, key_path, 0, winreg.KEY_SET_VALUE)
# 設(shè)置代理服務(wù)器
if enable_proxy:
winreg.SetValueEx(key, "ProxyServer", 0, winreg.REG_SZ, proxy_server)
winreg.SetValueEx(key, "ProxyEnable", 0, winreg.REG_DWORD, 1)
else:
# 關(guān)閉代理
winreg.SetValueEx(key, "ProxyEnable", 0, winreg.REG_DWORD, 0)
# 刷新代理設(shè)置
INTERNET_OPTION_REFRESH = 37
INTERNET_OPTION_SETTINGS_CHANGED = 39
internet_set_option = ctypes.windll.Wininet.InternetSetOptionW
internet_set_option(0, INTERNET_OPTION_REFRESH, 0, 0)
internet_set_option(0, INTERNET_OPTION_SETTINGS_CHANGED, 0, 0)
# 關(guān)閉注冊表鍵
winreg.CloseKey(key)
print("系統(tǒng)代理設(shè)置成功!")
except Exception as e:
print(f"設(shè)置系統(tǒng)代理失敗: {e}")
if __name__ == "__main__":
# 設(shè)置代理(啟用代理)
set_proxy(enable_proxy=True, proxy_address="http://127.0.0.1:8080")
# 設(shè)置代理(關(guān)閉代理)
# set_proxy(enable_proxy=False)
安裝證書(certutil.exe -addstore root mitmproxy-ca-cert.cer)
import subprocess
import platform
def is_mitmproxy_cert_installed():
try:
# 使用 PowerShell 檢查證書是否存在
res = subprocess.check_output(['powershell',
'Get-ChildItem -Path Cert:\CurrentUser\Root | Where-Object {$_.Subject -like "*mitmproxy*"}'])
if res:
return True
return False
except subprocess.CalledProcessError as e:
return False
def install_mitmproxy_certificate(cert_path):
system_platform = platform.system()
if system_platform == "Windows":
# Windows系統(tǒng)下使用certutil命令
try:
res = subprocess.run(["certutil.exe", "-addstore", "root", cert_path], check=True, capture_output=True,
text=True)
print(res)
print("Mitmproxy證書已成功安裝到根證書存儲中。")
except subprocess.CalledProcessError as e:
print(f"安裝Mitmproxy證書失敗: {e}")
if __name__ == "__main__":
if is_mitmproxy_cert_installed():
print("Mitmproxy證書已安裝")
else:
print("Mitmproxy證書未安裝")
# 替換為實際的證書路徑
certificate_path = r"mitmproxy-ca-cert.cer"
install_mitmproxy_certificate(certificate_path)
# "certmgr.msc"
運行
可以用 mitmproxy、mitmdump、mitmweb 這三個命令中的任意一個
mitmproxy(只能在命令行窗口)命令啟動后,會提供一個命令行界面,用戶可以實時看到發(fā)生的請求,并通過命令過濾請求,查看請求數(shù)據(jù)mitmweb命令啟動后,會提供一個 web 界面,用戶可以實時看到發(fā)生的請求,并通過 GUI 交互來過濾請求,查看請求數(shù)據(jù)mitmdump命令啟動后,沒有界面,結(jié)合自定義腳本,默默工作
代碼啟動
方式一
import os
import set_proxy
if __name__ == '__main__':
try:
set_proxy(enable_proxy=True, proxy_address="http://127.0.0.1:8080")
os.system("mitmweb")
# os.system("mitmdump -s .\my_script.py")
except KeyboardInterrupt:
set_proxy(enable_proxy=False)
方式二
import asyncio
import os
from mitmproxy import options
from mitmproxy.tools.dump import DumpMaster
import set_proxy
import my_script
async def start_mitmproxy():
opts = options.Options(listen_host='0.0.0.0', listen_port=8080)
master = DumpMaster(opts)
master.addons.add(my_script)
await master.run()
if __name__ == '__main__':
try:
set_proxy(enable_proxy=True, proxy_address="http://127.0.0.1:8080")
asyncio.run(start_mitmproxy())
except KeyboardInterrupt:
set_proxy(enable_proxy=False)
腳本
需要根據(jù)需求開發(fā)
- 查官方文檔:https://docs.mitmproxy.org/stable/
- 腳本示例:https://github.com/mitmproxy/mitmproxy/tree/master/examples
方式一:編寫一個 py 文件,文件中定義了若干鉤子函數(shù)(可查 https://docs.mitmproxy.org/stable/api/events.html)
主要是request和response修改請求響應(yīng)等
import logging
import mitmproxy.http
num = 0
def request(flow: mitmproxy.http.HTTPFlow):
global num
num = num + 1
print("We've seen %d flows" % num)
方式二:編寫一個 py文件,文件定義了變量 addons插件列表,addons 是個數(shù)組,每個元素是一個類實例,這些類有若干方法,這些方法實現(xiàn)了某些 mitmproxy 提供的鉤子事件。
import logging
class Counter:
def __init__(self):
self.num = 0
def request(self, flow):
self.num = self.num + 1
logging.info("We've seen %d flows" % self.num)
addons = [Counter()]
更多實例前往github查看 腳本示例。
這里記錄一個重訂向url的獲取:用requests可以直接拿到resp.url 或者使用 flow.response.headers.get(“location”)
到此這篇關(guān)于python+mitmproxy抓包的實現(xiàn)的文章就介紹到這了,更多相關(guān)python mitmproxy抓包內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python中TypeError: int object is not 
在Python中,當(dāng)你嘗試對一個非迭代對象(如整數(shù)、浮點數(shù)等)使用迭代操作(如for循環(huán)、列表推導(dǎo)式中的迭代等)時,會觸發(fā)TypeError: 'int' object is not iterable錯誤,所以本文給大家介紹了Python中TypeError: int object is not iterable錯誤分析及解決辦法2024-08-08
Anaconda+vscode+pytorch環(huán)境搭建過程詳解
這篇文章主要介紹了Anaconda+vscode+pytorch環(huán)境搭建過程詳解,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-05-05
Python函數(shù)式編程指南(一):函數(shù)式編程概述
這篇文章主要介紹了Python函數(shù)式編程指南(一):函數(shù)式編程概述,本文講解了什么是函數(shù)式編程概述、什么是函數(shù)式編程、為什么使用函數(shù)式編程、如何辨認(rèn)函數(shù)式風(fēng)格等核心知識,需要的朋友可以參考下2015-06-06
python利用appium實現(xiàn)手機APP自動化的示例
這篇文章主要介紹了python利用appium實現(xiàn)手機APP自動化的示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01
python內(nèi)置函數(shù)sorted()用法深入分析
這篇文章主要介紹了python內(nèi)置函數(shù)sorted()用法,結(jié)合實例形式較為深入的分析了Python內(nèi)置函數(shù)sorted()功能、使用方法及相關(guān)操作注意事項,需要的朋友可以參考下2019-10-10
python實現(xiàn)提取COCO,VOC數(shù)據(jù)集中特定的類
這篇文章主要介紹了python實現(xiàn)提取COCO,VOC數(shù)據(jù)集中特定的類,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-03-03
python transpose()處理高維度數(shù)組的軸變換的實現(xiàn)
本文主要介紹了python transpose()處理高維度數(shù)組的軸變換的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-09-09

