本页依照官方说明组织内容,侧重概念、配置步骤与验证方式。

官方资料继续:总结

总结

官方资料指出,这个诊断脚本可帮你从"代理不行了"这个模糊的描述,精确到"HTTP 端口 7890 不可达"或"15 个网络节点中 12 个超时"这样可操作的结论。保存到桌面,出典型典型疑问时鼠标双击即可。

官方资料继续:进阶:定时诊断 + 健康评分

进阶:定时诊断 + 健康评分

扩展脚本,每小时自动诊断并记录健康评分:

# 在脚本末尾追加
def health_score():
    total, failed = len(results), sum(1 for r in results if r[1] == FAIL)
    if total == 0:
        return 0
    score = round((1 - failed / total) * 100)
    return score

score = health_score()
print(f"\n健康评分: {score}/100")

# 写入日志
from datetime import datetime
with open("clash-health.log", "a") as f:
    f.write(f"{datetime.now().isoformat()} score={score} failed={failed}\n")

配合 crontab 定时运行:

# 每小时诊断一次
0 * * * * python3 /opt/scripts/clash-diag.py >> /var/log/clash-diag.log 2>&1

官方资料继续:各检查项的修复建议

各检查项的修复建议

检查项 FAIL 常见原因 修复
核心引擎存活 mihomo 未启动或崩溃 重启 Clash Verge;查看日志
HTTP/SOCKS 端口 端口被其他程序占用 netstat -ano 查占用;换端口
DNS 解析 系统 DNS 故障 刷新 DNS 缓存;检查 Clash DNS 参数方案
代理可达性(国内) 代理策略集错误,国内走代理 检查 GEOIP,CN,DIRECT 策略集
代理可达性(海外) 所有网络节点不可用 迭代发行分支迭代订阅;检查网络节点参数方案
网络节点全超时 订阅失效或网络隔离 手动迭代发行分支迭代订阅;检查网络基础连接
Provider 无数据 订阅 URL 失效 检查 URL 可达性;迭代发行分支迭代订阅

官方资料继续:典型诊断输出解读

典型诊断输出解读

输出示例一:一切正常

==================================================
  Clash Verge 自动诊断
  DESKTOP-PC / Windows
==================================================

[1/8] 进程检查
  [OK] 内核存活: API 端口 9090 可达
[2/8] 端口检查
  [OK] HTTP 代理: HTTP 端口 7890 可达
  [OK] SOCKS5 代理: SOCKS5 端口 7891 可达
[3/8] DNS 检查
  [OK] DNS 解析: www.baidu.com=110.242.68.66, www.google.com=142.250.x.x, github.com=140.82.x.x
[4/8] 代理连通性
  [OK] 代理可达性: 国内 & 海外 均可访问
[5/8] 节点状态
  [OK] 代理节点: 总数=15 存活=12 超时=3
[6/8] 订阅状态
  [OK] Provider: main(15节点)
[7/8] 配置检查
  [OK] 当前配置: mode=rule port=7890
[8/8] 系统环境
  [OK] 系统环境: OS=Windows 10; Python=3.12.0

==================================================
  诊断通过,Clash 代理运行正常
==================================================

输出示例二:有典型典型疑问

[1/8] 进程检查
  [FAIL] 内核存活: API 端口 9090 无响应
[4/8] 代理连通性
  [FAIL] 代理可达性: 国内=ConnectionError; 海外=ConnectionError
[5/8] 节点状态
  [FAIL] 代理节点: 总数=0 存活=0 超时=0

==================================================
  发现 3 个问题:
    - 内核存活: API 端口 9090 无响应
    - 代理可达性: 国内=ConnectionError; 海外=ConnectionError
    - 代理节点: 总数=0 存活=0 超时=0
==================================================

-> 确认 Clash 内核未运行。建议:启动 Clash Verge 并检查日志。

官方资料继续:诊断脚本:全覆盖版

诊断脚本:全覆盖版

以下脚本覆盖 8 个常见检查项,运行后输出清晰的结论和建议:

#!/usr/bin/env python3
"""Clash Verge 一键诊断脚本"""

import requests
import socket
import subprocess
import platform
import sys
import json
from urllib.request import urlopen

API = "http://127.0.0.1:9090"
HTTP_PORT = 7890
SOCKS_PORT = 7891
PASS, FAIL, WARN = "OK", "FAIL", "WARN"

results = []

def check(name, fn):
    try:
        ok, detail = fn()
        status = PASS if ok else FAIL
        results.append((name, status, detail))
        print(f"  [{status}] {name}: {detail}")
        return ok
    except Exception as e:
        results.append((name, FAIL, str(e)))
        print(f"  [FAIL] {name}: {e}")
        return False

def check_port_open(port, name):
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.settimeout(3)
        s.connect(("127.0.0.1", port))
        s.close()
        return True, f"{name} 端口 {port} 可达"
    except:
        return False, f"{name} 端口 {port} 不可达"

def get_proxies():
    try:
        resp = requests.get(f"{API}/proxies", timeout=5)
        return resp.json().get("proxies", {})
    except:
        return {}

print("=" * 50)
print("  Clash Verge 自动诊断")
print("  " + platform.node() + " / " + platform.system())
print("=" * 50)

# 1. 内核进程
print("\n[1/8] 进程检查")
check("内核存活", lambda: (
    True if check_port_open(9090, "API")[0] else (False, "API 端口 9090 无响应")
))

# 2. 代理端口
print("\n[2/8] 端口检查")
check("HTTP 代理", lambda: check_port_open(HTTP_PORT, "HTTP"))
check("SOCKS5 代理", lambda: check_port_open(SOCKS_PORT, "SOCKS5"))

# 3. DNS 解析
print("\n[3/8] DNS 检查")
def check_dns():
    ips = []
    for domain in ["www.baidu.com", "www.google.com", "github.com"]:
        try:
            ip = socket.getaddrinfo(domain, 443)[0][4][0]
            ips.append(f"{domain}={ip}")
        except:
            ips.append(f"{domain}=FAIL")
    all_ok = "FAIL" not in "".join(ips)
    return all_ok, ", ".join(ips)
check("DNS 解析", check_dns)

# 4. 代理连通性
print("\n[4/8] 代理连通性")
def check_proxy_conn():
    errors = []
    for name, url in [("国内", "https://www.baidu.com"), ("海外", "https://www.google.com")]:
        try:
            resp = requests.get(url, proxies={"http": f"http://127.0.0.1:{HTTP_PORT}", "https": f"http://127.0.0.1:{HTTP_PORT}"}, timeout=8)
            if resp.status_code != 200:
                errors.append(f"{name}={resp.status_code}")
        except Exception as e:
            errors.append(f"{name}={e.__class__.__name__}")
    if not errors:
        return True, "国内 & 海外 均可访问"
    return False, "; ".join(errors)
check("代理可达性", check_proxy_conn)

# 5. 节点状态
print("\n[5/8] 节点状态")
def check_nodes():
    proxies = get_proxies()
    total, live, dead = 0, 0, 0
    for name, p in proxies.items():
        if p["type"] in ("Direct", "Reject"):
            continue
        total += 1
        h = p.get("history", [])
        if h and h[-1].get("delay", 0) > 0:
            live += 1
        else:
            dead += 1
    if total == 0:
        return False, "没有代理节点"
    return live > 0, f"总数={total} 存活={live} 超时={dead}"
check("代理节点", check_nodes)

# 6. 订阅/Provider
print("\n[6/8] 订阅状态")
def check_providers():
    try:
        resp = requests.get(f"{API}/providers/proxies", timeout=5)
        providers = resp.json()
        if not providers:
            return True, "无 Provider(可能使用本地配置)"
        details = []
        for name, info in providers.items():
            count = len(info.get("proxies", []))
            details.append(f"{name}({count}节点)")
        return True, ", ".join(details)
    except:
        return False, "无法获取 Provider 信息"
check("Provider", check_providers)

# 7. 配置语法
print("\n[7/8] 配置检查")
def check_config():
    try:
        resp = requests.get(f"{API}/configs", timeout=5)
        config = resp.json()
        mode = config.get("mode", "N/A")
        port = config.get("port", "N/A")
        return True, f"mode={mode} port={port}"
    except:
        return False, "无法获取配置信息"
check("当前配置", check_config)

# 8. 系统环境
print("\n[8/8] 系统环境")
def check_system():
    info = []
    info.append(f"OS={platform.system()} {platform.release()}")
    try:
        info.append(f"Python={platform.python_version()}")
    except:
        pass
    # 检查系统代理
    if platform.system() == "Windows":
        try:
            result = subprocess.run(["netsh", "winhttp", "show", "proxy"], capture_output=True, text=True, timeout=5)
            if "127.0.0.1:7890" in result.stdout:
                info.append("系统代理=已设置")
            else:
                info.append("系统代理=未设置(正常)")
        except:
            pass
    return True, "; ".join(info)
check("系统环境", check_system)

# 总结
print("\n" + "=" * 50)
failed = [r for r in results if r[1] == FAIL]
if not failed:
    print("  诊断通过,Clash 代理运行正常")
elif len(failed) <= 2:
    print(f"  发现 {len(failed)} 个问题:")
    for name, _, detail in failed:
        print(f"    - {name}: {detail}")
else:
    print(f"  发现 {len(failed)} 个问题,建议重启 Clash 后重试")
print("=" * 50)

保存为 clash-diag.py,运行:

python3 clash-diag.py

官方资料继续:为什么需要自动诊断?

为什么需要自动诊断?

代理出典型典型疑问时,排查方向可能有十几种:核心引擎挂了?端口被占?DNS 不通?网络节点全挂了?订阅失效了?依次手动检查耗时不说,还可能漏掉关键环节。

本文给出一套 Python 诊断脚本,一键运行,自动定位 90% 的常见代理故障。

以上为官方说明中的关键内容,建议结合当前阶段发行分支逐项核对。