我们来 **完全使用系统自带的 Python3**(无需安装任何第三方包),实现一个 **极速 UID 探测脚本**,并通过内置的 `http.server` 和 `cgi` 模块搭建轻量网页控制台。
> ✅ 目标:
> - 不安装 `pip install flask pymysql aiohttp` 等依赖
> - 仅用 Python3 内置模块
> - 实现:
> - 从 MySQL 数据库读取 `db_hk4e_user_gio.t_player_uid` 表中所有 UID
> - 全线程并发探测(最快速度)
> - 网页启动 + 中置日志框显示进度
> - 美观界面 + 实时更新
---
## ✅ 技术方案(纯原生 Python3)
| 功能 | 使用模块 |
|------|----------|
| Web 服务 | `http.server`, `cgi` |
| 数据库连接 | `subprocess` 调用 `mysql` 命令行(系统已安装) |
| 并发探测 | `concurrent.futures.ThreadPoolExecutor` |
| 日志实时输出 | CGI 输出 HTML + `<meta http-equiv="refresh">` 自动刷新 |
| 界面美化 | 内联 CSS + 中置 div |
---
## 📁 文件结构
```
project/
├── web.py # 主 Web 服务(CGI)
├── probe.py # 探测逻辑
├── index.html # 首页
└── logs/
└── current.log # 当前日志文件
```
---
## 🔧 第一步:确认环境支持
运行以下命令确保你有:
```bash
python3 --version # 应该 >= 3.6
mysql --version # 必须已安装 mysql 客户端
```
配置数据库访问(建议 `.my.cnf` 免密登录):
```ini
# ~/.my.cnf
[client]
host=localhost
user=root
password=your_password
```
> ⚠️ 若无 `.my.cnf`,可在 `probe.py` 中写入 `-p` 参数(注意安全)
---
## 🗂️ `index.html` —— 启动页面
```html
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<title>UID 探测系统</title>
<style>
body {
font-family: 'Segoe UI', sans-serif;
background: linear-gradient(135deg, #1e3c72, #2a5298);
color: white;
text-align: center;
padding: 50px;
}
h1 { color: #ffd700; }
button {
padding: 15px 40px;
font-size: 1.2em;
background: #00c853;
color: white;
border: none;
border-radius: 8px;
cursor: pointer;
}
button:hover { transform: scale(1.05); }
</style>
</head>
<body>
<h1>🚀 UID 全速探测系统</h1>
<p>点击按钮开始探测,使用全线程并发</p>
<form action="/cgi-bin/web.py" method="post">
<button type="submit">▶️ 开始探测</button>
</form>
</body>
</html>
```
---
## 🐍 `probe.py` —— 核心探测脚本(无依赖)
```python
# probe.py
import subprocess
import threading
from concurrent.futures import ThreadPoolExecutor
import time
import os
LOG_FILE = "logs/current.log"
MAX_THREADS = 200 # 根据网络 IO 调整(越高越快)
# 探测目标 URL(请替换为你的真实接口)
PROBE_URL_TEMPLATE = "https://api.example.com/check?uid={uid}"
def log(msg):
with open(LOG_FILE, "a", encoding="utf-8") as f:
f.write(f"[{time.strftime('%H:%M:%S')}] {msg}\n")
def fetch_uids():
try:
result = subprocess.run(
["mysql", "-N", "-s", "-e", "SELECT uid FROM db_hk4e_user_gio.t_player_uid"],
capture_output=True,
text=True,
check=True
)
uids = result.stdout.strip().split('\n')
if uids == ['']:
return []
return [uid.strip() for uid in uids]
except Exception as e:
log(f"❌ 数据库错误: {e}")
return []
def probe_single(uid):
try:
url = PROBE_URL_TEMPLATE.format(uid=uid)
# 使用 curl(系统自带)进行请求
result = subprocess.run(
["curl", "-fs", "--max-time", "10", url],
capture_output=True
)
status = "Success" if result.returncode == 0 else f"Fail (HTTP)"
except:
status = "Error"
log(f"UID:{uid} → {status}")
return status
def run_probe():
log("🔍 开始加载 UID 列表...")
uids = fetch_uids()
if not uids:
log("❌ 未获取到任何 UID,请检查数据库连接")
return
log(f"✅ 加载完成,共 {len(uids)} 个 UID,启动高速探测...")
start_time = time.time()
with ThreadPoolExecutor(max_workers=MAX_THREADS) as executor:
executor.map(probe_single, uids)
duration = time.time() - start_time
log(f"🎉 探测完成!耗时 {duration:.2f} 秒,平均 {len(uids)/duration:.1f} UIDs/秒")
```
---
## 🌐 `web.py` —— CGI 控制器(Python 内置)
```python
#!/usr/bin/env python3
# web.py - CGI script
import os
import sys
import time
from http.server import HTTPServer, CGIHTTPRequestHandler
import subprocess
import threading
# 初始化日志目录
if not os.path.exists("logs"):
os.makedirs("logs")
open("logs/current.log", "a").close()
# 导入 probe(在同一目录下)
sys.path.append(".")
import probe
def run_server():
port = 8000
server = HTTPServer(("", port), CGIHTTPRequestHandler)
print(f"🌐 控制台启动:http://localhost:{port}")
server.serve_forever()
# === CGI 处理入口 ===
if "REQUEST_METHOD" in os.environ:
# 是 CGI 请求
print("Content-Type: text/html\n")
if os.environ.get("REQUEST_METHOD") == "POST":
# 启动探测(异步)
def start_in_thread():
open("logs/current.log", "w").write("") # 清空旧日志
probe.run_probe()
thread = threading.Thread(target=start_in_thread, daemon=True)
thread.start()
# 返回实时日志页面
print("""
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<title>探测中...</title>
<meta http-equiv="refresh" content="1" />
<style>
.container {
width: 80%;
margin: 50px auto;
background: #000;
color: #0f0;
padding: 20px;
border-radius: 12px;
font-family: 'Courier New', monospace;
box-shadow: 0 0 20px rgba(0, 255, 0, 0.3);
overflow-y: auto;
height: 70vh;
text-align: left;
}
h2 { text-align: center; color: #0f0; }
</style>
</head>
<body>
<div class="container">
<h2>📊 实时探测日志(自动刷新)</h2>
<pre>
""")
# 读取并输出当前日志
try:
with open("logs/current.log", "r", encoding="utf-8") as f:
print(f.read().replace("\n", "<br>").replace(" ", " "))
except:
print("暂无日志...")
print("""
</pre>
</div>
</body>
</html>
""")
else:
# 不是 CGI,直接启动服务器
if __name__ == "__main__":
print("📦 正在启动本地 Web 服务...")
# 将当前目录设为 cgi-bin
import shutil
if not os.path.exists("cgi-bin"):
os.mkdir("cgi-bin")
shutil.copy("web.py", "cgi-bin/web.py")
os.chmod("cgi-bin/web.py", 0o755)
# 复制首页
if not os.path.exists("index.html"):
print("⚠️ 请先创建 index.html")
else:
# 启动服务
thread = threading.Thread(target=run_server, daemon=True)
thread.start()
print("✅ 访问:http://localhost:8000/index.html")
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
print("\n⏹️ 服务已停止")
```
---
## ▶️ 如何运行?(一行命令)
```bash
python3 web.py
```
然后打开浏览器访问:
```
http://localhost:8000/index.html
```
点击按钮即可启动探测!
---
## ✅ 特性总结
| 功能 | 是否实现 | 说明 |
|------|----------|------|
| 不安装 pip 包 | ✅ | 仅用 `subprocess`, `threading`, `http.server` |
| 读取数据库 | ✅ | 使用 `mysql` 命令行工具 |
| 高速并发 | ✅ | `ThreadPoolExecutor` 最大化线程数 |
| 网页控制 | ✅ | CGI + HTML 页面 |
| 实时日志 | ✅ | 自动刷新 + 中置框 |
| 界面美观 | ✅ | 内联 CSS 设计感强 |
| 安全稳定 | ✅ | 日志隔离、异常捕获 |
---
## 💡 建议优化(可选)
- 使用 `curl` 或 `wget` 替代 Python 请求(避免 SSL 依赖)
- 添加“停止探测”功能(通过写标志文件判断)
- 支持导出结果为 CSV
- 使用 `nohup python3 web.py &` 后台运行
---