#!/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(): """测试网络连通性并返回 IP 信息""" import requests results = { "timestamp": datetime.now().isoformat(), "status": "ok" } # 获取直连 IP try: resp = requests.get("https://ifconfig.me/ip", timeout=5) results['direct_ip'] = resp.text.strip() except Exception as e: results['direct_ip'] = f"Error: {str(e)}" # 获取 WARP 代理 IP try: proxies = {'http': 'socks5://127.0.0.1:40000', 'https': 'socks5://127.0.0.1:40000'} # 使用 ifconfig.me 因为它只返回 IP,比 httpbin 更纯净 resp = requests.get("https://ifconfig.me/ip", proxies=proxies, timeout=8) results['warp_ip'] = resp.text.strip() results['warp_status'] = "connected" except Exception as e: results['warp_ip'] = None results['warp_error'] = str(e) results['warp_status'] = "failed" # 获取 Tor 代理 IP try: proxies = {'http': 'socks5://127.0.0.1:9050', 'https': 'socks5://127.0.0.1:9050'} resp = requests.get("https://ifconfig.me/ip", proxies=proxies, timeout=10) results['tor_ip'] = resp.text.strip() results['tor_status'] = "connected" except Exception as e: results['tor_ip'] = None results['tor_error'] = str(e) results['tor_status'] = "failed" # 为了兼容旧的验证脚本,把主要 IP 放在 ip_info if results.get('warp_ip'): results['ip_info'] = results['warp_ip'] elif results.get('tor_ip'): results['ip_info'] = results['tor_ip'] else: results['ip_info'] = results['direct_ip'] return jsonify(results) @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)