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"
合作推薦 訂閱連結從哪來? 本站合作機場註冊即送 1GB 香港高速體驗流量,可直接一鍵匯入。 取得高速節點

示例二:自動選擇延遲最低的節點

$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 的流式輸出,比輪詢更高效。