Clash 的外部控制 API(默认 127.0.0.1:9090)让一切界面操作都可以脚本化。本文给出几个拿来即用的自动化示例,Windows 用户用 PowerShell 即可,无需安装任何东西。

示例一:查询与切换节点

# 查看“节点选择”组当前状态(URL 中文需编码,PowerShell 会自动处理)
Invoke-RestMethod "http://127.0.0.1:9090/proxies/节点选择"

# 切换到指定节点
Invoke-RestMethod -Method Put -Uri "http://127.0.0.1:9090/proxies/节点选择" -Body '{"name":"香港 01"}' -ContentType "application/json"

示例二:自动选择延迟最低的节点

$group = "节点选择"
$info = Invoke-RestMethod "http://127.0.0.1:9090/proxies/$group"
$best = $null; $bestDelay = [int]::MaxValue
foreach ($name in $info.all) {
  try {
    $r = Invoke-RestMethod ("http://127.0.0.1:9090/proxies/$name/delay?timeout=3000&url=" +
      [uri]::EscapeDataString("http://www.gstatic.com/generate_204"))
    if ($r.delay -lt $bestDelay) { $bestDelay = $r.delay; $best = $name }
  } catch {}
}
if ($best) {
  Invoke-RestMethod -Method Put -Uri "http://127.0.0.1:9090/proxies/$group" -Body (@{name=$best} | ConvertTo-Json) -ContentType "application/json"
  "switched to $best ($bestDelay ms)"
}

把脚本保存为 .ps1,用任务计划程序设置“每小时运行”,就得到了一个比 url-test 更可控的自动选优器(比如只在特定时段运行)。

示例三:一键断开全部连接

Invoke-RestMethod -Method Delete "http://127.0.0.1:9090/connections"

切换节点后强制所有连接重建,等价于界面上的“关闭全部连接”。

示例四:切换出站模式

Invoke-RestMethod -Method Patch -Uri "http://127.0.0.1:9090/configs" -Body '{"mode":"Global"}' -ContentType "application/json"

要点

  • 设置了 secret 的话,所有请求加头:-Headers @{Authorization = "Bearer 你的密钥"}
  • 完整端点列表见外部控制 API 入门
  • API 修改的是运行时状态,配置重载后恢复为配置文件的值。
提示:做仪表盘、流量提醒等长驻监控时,用 GET /trafficGET /connections 的流式输出,比轮询更高效。