clash_api.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. #!/usr/bin/env python3
  2. import requests
  3. import json
  4. # -------- 配置部分 --------
  5. API_URL = "http://127.0.0.1:9097" # Clash 本地 API
  6. API_KEY = "esZnx8" # Clash API 密钥
  7. GROUP_NAME = "♻️ 手动切换" # 要轮换的策略组名称
  8. # ---------------------------
  9. headers = {
  10. "Authorization": f"Bearer {API_KEY}",
  11. "Content-Type": "application/json"
  12. }
  13. def get_proxies():
  14. """获取策略组和节点信息"""
  15. resp = requests.get(f"{API_URL}/proxies", headers=headers, timeout=5)
  16. resp.raise_for_status()
  17. return resp.json()
  18. def switch_next_node():
  19. proxies = get_proxies().get('proxies')
  20. if GROUP_NAME not in proxies:
  21. print(f"策略组 '{GROUP_NAME}' 不存在")
  22. return
  23. group = proxies[GROUP_NAME]
  24. all_nodes = group['all']
  25. current_node = group['now']
  26. # 找到下一个节点
  27. try:
  28. idx = all_nodes.index(current_node)
  29. next_idx = (idx + 1) % len(all_nodes)
  30. next_node = all_nodes[next_idx]
  31. except ValueError:
  32. # 当前节点不在列表里,选择第一个
  33. next_node = all_nodes[0]
  34. # 切换节点(注意 API 路径修改)
  35. data = {"name": next_node}
  36. resp = requests.put(f"{API_URL}/proxies/{GROUP_NAME}", headers=headers, json=data, timeout=5)
  37. resp.raise_for_status()
  38. print(f"[OK] 策略组 '{GROUP_NAME}' 切换完成")
  39. print(f" 当前节点: {current_node} → {next_node}")
  40. return next_node
  41. if __name__ == "__main__":
  42. switch_next_node()