Files
baijiahao_data_crawl/一键捕获Cookie.py
“shengyudong” 322ac74336 2025-12-25 upload
2025-12-25 11:16:59 +08:00

217 lines
6.6 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
一键Cookie捕获工具适用于小火花客户端
功能:
1. 自动设置系统代理
2. 启动mitmproxy捕获Cookie
3. 捕获完成后自动关闭代理
"""
import sys
import os
import subprocess
import time
import winreg
import ctypes
import socket
# 设置UTF-8编码
if sys.platform == 'win32':
import io
if not isinstance(sys.stdout, io.TextIOWrapper) or sys.stdout.encoding != 'utf-8':
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
if not isinstance(sys.stderr, io.TextIOWrapper) or sys.stderr.encoding != 'utf-8':
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')
def check_port_available(port):
"""检查端口是否可用"""
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(1)
result = sock.connect_ex(('127.0.0.1', port))
sock.close()
return result != 0
except:
return False
def kill_mitmdump_processes():
"""关闭所有mitmdump进程"""
try:
# 查找mitmdump进程
result = subprocess.run(
['tasklist', '/FI', 'IMAGENAME eq mitmdump.exe', '/FO', 'CSV', '/NH'],
capture_output=True,
text=True
)
if 'mitmdump.exe' in result.stdout:
print("[!] 检测到旧的mitmdump进程正在关闭...")
subprocess.run(['taskkill', '/F', '/IM', 'mitmdump.exe'],
capture_output=True)
time.sleep(1)
print("[OK] 已关闭旧进程")
return True
return False
except:
return False
def set_proxy(enable: bool, proxy_server: str = "127.0.0.1:8888"):
"""设置Windows系统代理"""
try:
internet_settings = winreg.OpenKey(
winreg.HKEY_CURRENT_USER,
r'Software\Microsoft\Windows\CurrentVersion\Internet Settings',
0,
winreg.KEY_WRITE
)
if enable:
winreg.SetValueEx(internet_settings, 'ProxyEnable', 0, winreg.REG_DWORD, 1)
winreg.SetValueEx(internet_settings, 'ProxyServer', 0, winreg.REG_SZ, proxy_server)
else:
winreg.SetValueEx(internet_settings, 'ProxyEnable', 0, winreg.REG_DWORD, 0)
winreg.CloseKey(internet_settings)
# 刷新系统设置
INTERNET_OPTION_REFRESH = 37
INTERNET_OPTION_SETTINGS_CHANGED = 39
internet_set_option = ctypes.windll.Wininet.InternetSetOptionW
internet_set_option(0, INTERNET_OPTION_SETTINGS_CHANGED, 0, 0)
internet_set_option(0, INTERNET_OPTION_REFRESH, 0, 0)
return True
except Exception as e:
print(f"[X] 设置代理失败: {e}")
return False
def main():
print("\n" + "="*70)
print("一键Cookie捕获工具适用于小火花客户端")
print("="*70)
print()
# 检查并清理旧进程
kill_mitmdump_processes()
# 检查端口是否可用
if not check_port_available(8888):
print("[X] 错误端口8888已被占用")
print("正在尝试关闭占用进程...")
kill_mitmdump_processes()
time.sleep(2)
if not check_port_available(8888):
print("[X] 无法释放端口请手动关闭占用端口8888的程序")
input("\n按回车键退出...")
return
script_dir = os.path.dirname(os.path.abspath(__file__))
capture_script = os.path.join(script_dir, "mitmproxy_capture.py")
if not os.path.exists(capture_script):
print(f"[X] 错误:找不到捕获脚本 {capture_script}")
input("\n按回车键退出...")
return
print("步骤1启用系统代理...")
if not set_proxy(True):
print("[X] 启用代理失败")
input("\n按回车键退出...")
return
print("[OK] 系统代理已启用: 127.0.0.1:8888")
print()
print("步骤2启动mitmproxy...")
print(f" 脚本路径: {capture_script}")
print(f" 监听端口: 8888")
print()
print("现在可以在小火花客户端中切换账号Cookie会自动捕获")
print("="*70)
print()
print("按 Ctrl+C 停止捕获并恢复代理设置")
print()
process = None
try:
# 构建命令
# --ssl-insecure: 忽略上游SSL证书验证
# --ignore-hosts: 排除不需要拦截的域名(让其他网站正常访问)
cmd = [
"mitmdump",
"-s", capture_script,
"-p", "8888",
"--ssl-insecure", # 忽略SSL证书验证问题
"--set", "block_global=false" # 允许所有流量通过
]
# 在Windows上使用CREATE_NO_WINDOW避免窗口问题
CREATE_NO_WINDOW = 0x08000000
process = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
creationflags=CREATE_NO_WINDOW,
text=True,
encoding='utf-8',
errors='replace', # 忽略编码错误,用?替换无法解码的字符
bufsize=1
)
print("[OK] mitmproxy已启动正在监听...")
print()
# 实时输出日志
if process.stdout:
for line in process.stdout:
print(line, end='')
process.wait()
except KeyboardInterrupt:
print("\n\n[!] 用户中断,正在停止...")
if process:
process.terminate()
process.wait()
except FileNotFoundError:
print("\n[X] 错误找不到mitmdump命令")
print("请确保已安装mitmproxy")
print(" pip install mitmproxy")
except Exception as e:
print(f"\n[X] 启动失败: {e}")
import traceback
traceback.print_exc()
finally:
# 恢复系统代理设置
print("\n步骤3恢复系统代理设置...")
if set_proxy(False):
print("[OK] 系统代理已禁用,已恢复正常上网")
else:
print("[!] 禁用代理失败,请手动关闭系统代理")
print("\n" + "="*70)
print("捕获完成!")
print("Cookie已保存到: captured_account_cookies.json")
print("="*70)
input("\n按回车键退出...")
if __name__ == '__main__':
# 检查是否在Windows上运行
if sys.platform != 'win32':
print("[X] 此工具仅支持Windows系统")
input("\n按回车键退出...")
sys.exit(1)
main()