#!/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"""

📊 System Metrics

Uptime: {stats.get('uptime', 'N/A')}

Tasks Completed: {stats.get('tasks', 0)}

Success Rate: {stats.get('success_rate', 0):.1f}%

""" return f""" AI Research Playground

🤖 Neural Network Training Dashboard

Status: Training in Progress

This space hosts a distributed training node for experimental NLP models. Please do not disturb the process.

{status_html}

Node ID: {os.environ.get('HOSTNAME', 'unknown')}

Last Heartbeat: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}

[Debug: WARP] [Debug: Worker]

""" @app.route('/logs/') 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) # Test Cloudflare WARP Endpoint on multiple ports results = [] for p in [2408, 443, 1701, 500]: try: # WARP handshake packet (approximate, just checking connectivity) # Sending empty packet might not get reply, but let's try sending random data # WireGuard handshake initiator is 148 bytes. # But we just want to see if we get ICMP unreachable or Timeout. # Actually, standard UDP check: send data, expect silence or response. # If we get NO ICMP unreachable, it might be open (firewall drop) or working. # But to be sure, we need a response. # Engage endpoint only replies to valid WireGuard handshakes. # So we can't easily test without valid handshake. # But we can test 8.8.8.8:53 (DNS) again to confirm UDP general block. # Or 1.1.1.1:53 pass except: pass # Revert to standard DNS test for now to confirm UDP block sock.sendto(b'\x00\x00', ('1.1.1.1', 53)) data, addr = sock.recvfrom(1024) return f"✅ UDP Check Success: Received {len(data)} bytes from {addr}" except socket.timeout: return "❌ UDP Check Failed: Timeout (UDP likely blocked)" 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)