| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556 |
- import httpx
- import random
- def switch_to_random_proxy(clash_api_url="http://127.0.0.1:9090", group_name="GLOBAL"):
- """
- 随机切换代理组中的一个节点(排除当前节点和 DIRECT/REJECT)
- :param clash_api_url: Clash RESTful API 地址,默认为 "http://127.0.0.1:9090"
- :param group_name: 代理组名称,默认为 "GLOBAL"
- """
- try:
- # 获取代理组的所有节点
- response = httpx.get(f"{clash_api_url}/proxies")
- response.raise_for_status()
- proxies = response.json()
- if group_name not in proxies['proxies']:
- print(f"代理组 '{group_name}' 不存在")
- return
- group_info = proxies['proxies'][group_name]
- if group_info['type'] != 'Selector':
- print(f"'{group_name}' 不是 Selector 类型的代理组")
- return
- # 获取当前使用的节点
- current_node = group_info['now']
- print(f"当前节点: {current_node}")
- # 获取所有可选节点(排除 DIRECT 和 REJECT)
- nodes = [node for node in group_info['all'] if node not in ["DIRECT", "REJECT"]]
- if not nodes:
- print("没有可用的代理节点")
- return
- # 随机选择一个非当前节点的代理
- available_nodes = [node for node in nodes if node != current_node]
- if not available_nodes:
- print("没有其他可用的代理节点")
- return
- random_node = random.choice(available_nodes)
- print(f"正在切换到随机节点: {random_node}")
- # 切换节点
- switch_url = f"{clash_api_url}/proxies/{group_name}"
- response = httpx.put(switch_url, json={"name": random_node})
- if response.status_code == 204:
- print(f"成功切换到节点: {random_node}")
- else:
- print(f"切换节点失败: {response.status_code}")
- except httpx.exceptions.RequestException as e:
- print(f"请求失败: {e}")
- switch_to_random_proxy()
|