random_proxy.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import httpx
  2. import random
  3. def switch_to_random_proxy(clash_api_url="http://127.0.0.1:9090", group_name="GLOBAL"):
  4. """
  5. 随机切换代理组中的一个节点(排除当前节点和 DIRECT/REJECT)
  6. :param clash_api_url: Clash RESTful API 地址,默认为 "http://127.0.0.1:9090"
  7. :param group_name: 代理组名称,默认为 "GLOBAL"
  8. """
  9. try:
  10. # 获取代理组的所有节点
  11. response = httpx.get(f"{clash_api_url}/proxies")
  12. response.raise_for_status()
  13. proxies = response.json()
  14. if group_name not in proxies['proxies']:
  15. print(f"代理组 '{group_name}' 不存在")
  16. return
  17. group_info = proxies['proxies'][group_name]
  18. if group_info['type'] != 'Selector':
  19. print(f"'{group_name}' 不是 Selector 类型的代理组")
  20. return
  21. # 获取当前使用的节点
  22. current_node = group_info['now']
  23. print(f"当前节点: {current_node}")
  24. # 获取所有可选节点(排除 DIRECT 和 REJECT)
  25. nodes = [node for node in group_info['all'] if node not in ["DIRECT", "REJECT"]]
  26. if not nodes:
  27. print("没有可用的代理节点")
  28. return
  29. # 随机选择一个非当前节点的代理
  30. available_nodes = [node for node in nodes if node != current_node]
  31. if not available_nodes:
  32. print("没有其他可用的代理节点")
  33. return
  34. random_node = random.choice(available_nodes)
  35. print(f"正在切换到随机节点: {random_node}")
  36. # 切换节点
  37. switch_url = f"{clash_api_url}/proxies/{group_name}"
  38. response = httpx.put(switch_url, json={"name": random_node})
  39. if response.status_code == 204:
  40. print(f"成功切换到节点: {random_node}")
  41. else:
  42. print(f"切换节点失败: {response.status_code}")
  43. except httpx.exceptions.RequestException as e:
  44. print(f"请求失败: {e}")
  45. switch_to_random_proxy()