本页围绕官网下载后的使用流程展开,先说明能力,再提供操作要点。
官网下载说明继续:基础:Clash API 速览
基础:Clash API 速览
Clash 核心组件暴露了丰富的 RESTful API,所有脚本操作的基础:
# 核心端点
GET /proxies # 所有代理节点及延迟
GET /proxies/{name} # 单个节点详情 + 延迟历史
GET /rules # 规则列表及匹配计数
GET /connections # 当前活动连接
GET /configs # 当前配置信息
PUT /configs # 重载配置(支持 force=true)
GET /providers/proxies # Provider 状态
PUT /providers/proxies/{name} # 更新指定 Provider
GET /group/{name} # 策略组信息
PUT /group/{name} # 切换策略组选择
认证:如果设置了 secret,请求头需带 Authorization: Bearer <secret>。
官网下载说明继续:脚本能做什么?
脚本能做什么?
Clash Verge 提供了 Clash API(默认 127.0.0.1:9090)和内置脚本引擎,适配用 Python/Node.js 脚本实现配置文件动态生成、运行状态监控、自动化切换等运维操作。
本文聚焦用脚本提升日常代理管理效率的实战技巧——不是讲 Clash 自带的 JavaScript 脚本可用能力,而是如何用外部脚本操作 Clash 的 API,实现自动化运维。
官网下载说明继续:Node.js 运维脚本实战
Node.js 运维脚本实战
实时流量 CLI 仪表盘
终端内动态刷新流量和连接数:
const http = require('http');
const API = 'http://127.0.0.1:9090';
function fetch(endpoint) {
return new Promise((resolve, reject) => {
http.get(`${API}${endpoint}`, res => {
let data = '';
res.on('data', c => data += c);
res.on('end', () => resolve(JSON.parse(data)));
}).on('error', reject).setTimeout(3000, reject);
});
}
function fmt(bytes) {
for (const u of ['B', 'KB', 'MB', 'GB'])
if (bytes < 1024) return `${bytes.toFixed(1)} ${u}`;
else bytes /= 1024;
return `${bytes.toFixed(1)} GB`;
}
setInterval(async () => {
const data = await fetch('/connections');
const up = data.uploadTotal, down = data.downloadTotal;
const cnt = data.connections.length;
const bar = (n, max) => '#'.repeat(Math.round(n / (up+down||1) * 50));
console.clear();
console.log(`=== Clash ${new Date().toLocaleTimeString()} ===`);
console.log(`Conns: ${cnt}`);
console.log(`Up: ${fmt(up)} ${bar(up, 50)}`);
console.log(`Down: ${fmt(down)} ${bar(down, 50)}`);
console.log(`Total:${fmt(up + down)}`);
}, 2000);
故障切换守护进程
监控代理健康状态,连续失败后自动触发恢复:
const http = require('http');
const API = 'http://127.0.0.1:9090';
let failCount = 0;
function get(url) {
return new Promise((resolve, reject) => {
http.get(url, { timeout: 3000 }, res => {
let d = '';
res.on('data', c => d += c);
res.on('end', () => resolve(JSON.parse(d)));
}).on('error', reject);
});
}
function put(url, body) {
return new Promise((resolve, reject) => {
const r = http.request(url, { method: 'PUT' }, res => resolve(res.statusCode));
r.write(JSON.stringify(body));
r.end();
r.on('error', reject);
});
}
async function check() {
try {
await get(`${API}/proxies`);
failCount = 0;
console.log(`[${new Date().toLocaleTimeString()}] OK`);
} catch(e) {
failCount++;
console.log(`[${new Date().toLocaleTimeString()}] Fail ${failCount}/3`);
if (failCount >= 3) {
// 尝试切换到 DIRECT 兜底
await put(`${API}/group/Proxy`, { name: 'DIRECT' });
failCount = 0;
}
}
}
setInterval(check, 30000);
check();
官网下载说明继续:Python 运维脚本实战
Python 运维脚本实战
脚本一:批量可用节点延迟报表
获取所有可用节点并按延迟排序,生成表格化报表:
import requests
from tabulate import tabulate
API = "http://127.0.0.1:9090"
AUTH = {"Authorization": "Bearer your-secret"}
def get_node_latency():
resp = requests.get(f"{API}/proxies", headers=AUTH, timeout=5)
data = resp.json()
nodes = []
for name, p in data.get("proxies", {}).items():
if p["type"] in ("Direct", "Reject", "Selector", "URLTest", "Fallback"):
continue
history = p.get("history", [])
delay = history[-1]["delay"] if history else -1
nodes.append((name, delay, p["type"]))
nodes.sort(key=lambda x: x[1] if x[1] > 0 else 99999)
return nodes
def print_report():
nodes = get_node_latency()
table = [
[i+1, name, f"{delay}ms" if delay > 0 else "TIMEOUT", ptype]
for i, (name, delay, ptype) in enumerate(nodes)
]
print(tabulate(table, headers=["#", "Node", "Delay", "Type"]))
if __name__ == "__main__":
print_report()
脚本二:自动切换到延迟最低可用节点
定时扫描可用节点延迟,自动将策略组切到最快可用节点:
import requests
API = "http://127.0.0.1:9090"
GROUP = "Proxy"
def switch_to_fastest():
resp = requests.get(f"{API}/group/{GROUP}", timeout=5)
group = resp.json()
proxies = group.get("all", [])
fastest, lowest = None, 99999
for node_name in proxies:
if node_name in ("DIRECT", "REJECT"):
continue
resp = requests.get(f"{API}/proxies/{node_name}", timeout=5)
node = resp.json()
history = node.get("history", [])
if history and history[-1]["delay"] > 0:
if history[-1]["delay"] < lowest:
lowest = history[-1]["delay"]
fastest = node_name
if fastest:
resp = requests.put(
f"{API}/group/{GROUP}",
json={"name": fastest}, timeout=5
)
if resp.status_code == 204:
print(f"Switched to: {fastest} ({lowest}ms)")
if __name__ == "__main__":
switch_to_fastest()
脚本三:连接监控 + 异常告警
实时监控连接数,超过阈值时输出 Top 告警目标:
import requests, time
from datetime import datetime
API = "http://127.0.0.1:9090"
ALERT = 100 # 连接数告警阈值
def monitor():
resp = requests.get(f"{API}/connections", timeout=5)
data = resp.json()
upload = data.get("uploadTotal", 0) / 1024 / 1024
download = data.get("downloadTotal", 0) / 1024 / 1024
conns = data.get("connections", [])
host_counts = {}
for conn in conns:
host = conn["metadata"]["host"]
host_counts[host] = host_counts.get(host, 0) + 1
top5 = sorted(host_counts.items(), key=lambda x: x[1], reverse=True)[:5]
print(f"[{datetime.now().strftime('%H:%M:%S')}] "
f"Conns: {len(conns)} | Up: {upload:.1f}MB | Down: {download:.1f}MB")
if len(conns) > ALERT:
print(f" ALERT: {len(conns)} connections")
for host, cnt in top5:
print(f" {host}: {cnt}")
if __name__ == "__main__":
while True:
try:
monitor()
except Exception as e:
print(f"Error: {e}")
time.sleep(10)
脚本四:Provider 并发批量升级
并且升级多个 Provider,减少等待时间:
import requests
from concurrent.futures import ThreadPoolExecutor
API = "http://127.0.0.1:9090"
def update_one(name):
try:
resp = requests.put(
f"{API}/providers/proxies/{name}", timeout=30
)
status = "OK" if resp.status_code == 204 else f"ERR {resp.status_code}"
print(f" {name}: {status}")
except Exception as e:
print(f" {name}: {e}")
def batch_update():
resp = requests.get(f"{API}/providers/proxies", timeout=5)
providers = list(resp.json().keys())
print(f"Updating {len(providers)} providers...")
with ThreadPoolExecutor(max_workers=5) as ex:
ex.map(update_one, providers)
if __name__ == "__main__":
batch_update()
官网下载说明继续:轻量运维面板
轻量运维面板
用 Python 内置 HTTP 服务器搭建一个简易可用节点状态面板:
from http.server import HTTPServer, BaseHTTPRequestHandler
import requests, json
CLASH = "http://127.0.0.1:9090"
def api(path):
return requests.get(f"{CLASH}{path}", timeout=5).json()
class Panel(BaseHTTPRequestHandler):
def do_GET(self):
if self.path != "/":
return self.send_response(404)
proxies = api("/proxies")["proxies"]
rows = ""
for name, p in proxies.items():
if p["type"] in ("Direct", "Reject"):
continue
h = p.get("history", [])
delay = h[-1]["delay"] if h else -1
color = "#4CAF50" if 0 < delay < 100 else "#FF9800" if delay > 0 else "#F44336"
rows += f'{name} {p["type"]} '
rows += f'{delay}ms '
html = f"""
Clash Verge 配合 Python/Node.js 脚本实现自动化运维 | clash Verge 官网下载 | clash Verge 官网下载
官网下载说明继续:定时任务集成
定时任务集成
Linux/macOS crontab
# 每 10 分钟自动切最快节点
*/10 * * * * python3 /opt/scripts/clash-auto-switch.py >> /var/log/clash-switch.log 2>&1
# 每小时更新所有 Provider
0 * * * * python3 /opt/scripts/clash-update-providers.py
# 每天凌晨生成昨日报表
0 1 * * * python3 /opt/scripts/clash-daily-report.py
Windows 计划任务
# PowerShell
$action = New-ScheduledTaskAction -Execute "python3" `
-Argument "C:\\scripts\\clash-auto-switch.py"
$trigger = New-ScheduledTaskTrigger -Once -At 00:00 `
-RepetitionInterval (New-TimeSpan -Minutes 10)
Register-ScheduledTask -TaskName "Clash Auto Switch" `
-Action $action -Trigger $trigger
官网下载说明继续:总结
总结
脚本运维的三个层次:
| 层次 | 场景 | 工具 |
|---|---|---|
| 数据采集 | 延迟监控、流量统计、连接分析 | Python requests + Clash API |
| 自动化控制 | 自动切换可用节点、批量升级 Provider、故障恢复 | Python/Node.js + crontab/计划任务 |
| 运维面板 | 实时状态查看、迅速操作入口 | SimpleHTTPServer 或轻量框架 |
最低投入:一个 Python 脚本 + crontab 定时任务,就能实现自动切换和定期升级。
官网下载说明继续:Clash Panel
Clash Panel
| Node | Type | Delay |
|---|
以上内容对应官网下载版本的使用场景,可直接用于后续配置参考。