cefrefdwe's picture
Upload WARP proxy tool with offline IP pool
8ae9296 verified
Raw History Blame Contribute Delete
7.01 kB
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
伪装面具 - 假网站
作用:启动一个极简的网页,应付平台健康检查,并提供日志查看接口
"""
from flask import Flask, jsonify, Response
import logging
import os
import json
from datetime import datetime
# 禁止 Flask 输出无关日志
log = logging.getLogger('werkzeug')
log.setLevel(logging.ERROR)
app = Flask(__name__)
# 统计数据(从 worker 共享)
stats_file = "/tmp/adfoc_stats.json"
def get_worker_stats():
"""获取 Worker 统计数据"""
try:
if os.path.exists(stats_file):
with open(stats_file, 'r') as f:
return json.load(f)
except:
pass
return None
def read_log_tail(filepath, n=100):
"""读取日志文件末尾 n 行"""
if not os.path.exists(filepath):
return f"Log file not found: {filepath}"
try:
with open(filepath, 'r', encoding='utf-8', errors='ignore') as f:
lines = f.readlines()
return "".join(lines[-n:])
except Exception as e:
return f"Error reading log: {str(e)}"
@app.route('/')
def home():
"""主页 - 伪装成 AI 研究项目"""
stats = get_worker_stats()
status_html = ""
if stats:
status_html = f"""
<div class="stats">
<h4>📊 System Metrics</h4>
<p>Uptime: {stats.get('uptime', 'N/A')}</p>
<p>Tasks Completed: {stats.get('tasks', 0)}</p>
<p>Success Rate: {stats.get('success_rate', 0):.1f}%</p>
</div>
"""
return f"""
<!DOCTYPE html>
<html>
<head>
<title>AI Research Playground</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {{
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
margin: 0;
padding: 40px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
}}
.container {{
background: white;
padding: 40px;
border-radius: 16px;
max-width: 600px;
margin: auto;
box-shadow: 0 20px 60px rgba(0,0,0,0.3);
}}
h3 {{
color: #333;
margin-top: 0;
}}
p {{
color: #666;
line-height: 1.6;
}}
.status {{
display: inline-block;
background: #10b981;
color: white;
padding: 4px 12px;
border-radius: 20px;
font-size: 14px;
}}
.stats {{
background: #f8fafc;
padding: 20px;
border-radius: 8px;
margin-top: 20px;
}}
.stats h4 {{
margin-top: 0;
color: #475569;
}}
.stats p {{
margin: 5px 0;
color: #334155;
}}
</style>
</head>
<body>
<div class="container">
<h3>🤖 Neural Network Training Dashboard</h3>
<p>Status: <span class="status">Training in Progress</span></p>
<p>This space hosts a distributed training node for experimental NLP models. Please do not disturb the process.</p>
{status_html}
<div style="margin-top: 30px; font-size: 12px; color: #999;">
<p>Node ID: {os.environ.get('HOSTNAME', 'unknown')}</p>
<p>Last Heartbeat: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}</p>
<p><a href="/logs/warp" style="color: #999;">[Debug: WARP]</a> <a href="/logs/worker" style="color: #999;">[Debug: Worker]</a></p>
</div>
</div>
</body>
</html>
"""
@app.route('/logs/<service>')
def view_logs(service):
"""查看日志 (仅供调试)"""
log_map = {
"warp": "/tmp/warp_manager.out.log",
"warp_err": "/tmp/warp_manager.err.log",
"worker": "/tmp/worker.out.log",
"worker_err": "/tmp/worker.err.log",
"super": "/tmp/supervisord.log"
}
if service not in log_map:
return "Invalid service name", 400
content = read_log_tail(log_map[service], n=200)
return Response(content, mimetype='text/plain')
@app.route('/test_network')
def test_network():
"""测试网络连通性"""
import subprocess
results = []
# Test 1: Cloudflare API (Direct)
try:
cmd = "curl -I -s --connect-timeout 5 https://api.cloudflareclient.com/v0a2405/reg"
output = subprocess.check_output(cmd, shell=True).decode('utf-8')
results.append(f"Direct -> Cloudflare API: OK\n{output}")
except subprocess.CalledProcessError as e:
results.append(f"Direct -> Cloudflare API: FAIL (Code {e.returncode})")
except Exception as e:
results.append(f"Direct -> Cloudflare API: ERROR ({str(e)})")
# Test 2: AdFoc (Direct)
try:
cmd = "curl -I -s --connect-timeout 5 http://adfoc.us"
output = subprocess.check_output(cmd, shell=True).decode('utf-8')
results.append(f"Direct -> AdFoc: OK\n{output}")
except subprocess.CalledProcessError as e:
results.append(f"Direct -> AdFoc: FAIL (Code {e.returncode})")
# Test 3: Local Proxy (if running)
try:
cmd = "curl -I -s --connect-timeout 5 --socks5 127.0.0.1:40000 http://adfoc.us"
output = subprocess.check_output(cmd, shell=True).decode('utf-8')
results.append(f"Proxy -> AdFoc: OK\n{output}")
except subprocess.CalledProcessError as e:
results.append(f"Proxy -> AdFoc: FAIL (Code {e.returncode})")
return Response("\n\n".join(results), mimetype='text/plain')
@app.route('/test_udp')
def test_udp():
"""测试 UDP 连通性 (DNS)"""
import socket
host = '8.8.8.8'
port = 53
timeout = 3
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.settimeout(timeout)
sock.sendto(b'\x00\x00', (host, port))
data, addr = sock.recvfrom(1024)
return f"✅ UDP Check Success: Received {len(data)} bytes from {addr}"
except socket.timeout:
return "❌ UDP Check Failed: Timeout"
except Exception as e:
return f"❌ UDP Check Failed: {e}"
finally:
sock.close()
@app.route('/ip')
def get_ip():
"""获取当前出口 IP"""
import subprocess
try:
ip = subprocess.check_output("curl -s ifconfig.me", shell=True).decode('utf-8')
return f"Current IP: {ip}"
except Exception as e:
return f"Error getting IP: {e}"
if __name__ == '__main__':
# 监听所有接口,端口 7860 (Hugging Face Space 默认端口)
app.run(host='0.0.0.0', port=7860)