clash_check_now_node.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import asyncio
  2. import httpx
  3. from typing import Optional, Dict, Any, List, Tuple
  4. async def check_now_node(url_and_port: str) -> Optional[str]:
  5. """检测当前节点并设置全局代理"""
  6. async with httpx.AsyncClient(timeout=10.0) as client:
  7. try:
  8. # 设置全局模式
  9. set_url = f"http://{url_and_port}/api/configs"
  10. set_data = {"mode": "Global"}
  11. set_response = await client.patch(set_url, json=set_data)
  12. set_response.raise_for_status()
  13. # 获取代理信息
  14. get_url = f"http://{url_and_port}/api/proxies"
  15. get_response = await client.get(get_url)
  16. get_response.raise_for_status()
  17. json_data = get_response.json()
  18. proxies: Dict[str, Any] = json_data.get("proxies", {})
  19. proxy_global: Dict[str, Any] = proxies.get("GLOBAL", {})
  20. now_proxy: Optional[str] = proxy_global.get("now")
  21. return now_proxy
  22. except httpx.HTTPError as exc:
  23. print(f"请求失败 {url_and_port}: {exc}")
  24. return None
  25. async def batch_check_nodes(ip: str, ports: List[str]) -> Dict[str, Optional[str]]:
  26. """批量检测节点"""
  27. tasks = [check_now_node(f"{ip}:{port}") for port in ports]
  28. results = await asyncio.gather(*tasks)
  29. return {
  30. f"{ip}:{port}": result
  31. for port, result in zip(ports, results)
  32. }
  33. def find_duplicate_nodes(results: Dict[str, Optional[str]]) -> List[Tuple[str, str]]:
  34. """查找重复的节点"""
  35. node_to_urls = {}
  36. for url, node in results.items():
  37. if node: # 只处理成功检测的节点
  38. if node not in node_to_urls:
  39. node_to_urls[node] = []
  40. node_to_urls[node].append(url)
  41. # 找出有重复的节点
  42. duplicates = []
  43. for node, urls in node_to_urls.items():
  44. if len(urls) > 1:
  45. for i in range(len(urls)):
  46. for j in range(i + 1, len(urls)):
  47. duplicates.append((urls[i], urls[j]))
  48. return duplicates
  49. if __name__ == "__main__":
  50. ip = '192.168.31.201'
  51. ports = [f'{58000 + i}' for i in range(1, 11)]
  52. results = asyncio.run(batch_check_nodes(ip, ports))
  53. # 输出所有节点信息
  54. for url, node in results.items():
  55. print(f"{url}: {node or '检测失败'}")
  56. # 检查并输出重复节点
  57. duplicates = find_duplicate_nodes(results)
  58. if duplicates:
  59. print("\n发现重复节点:")
  60. for url1, url2 in duplicates:
  61. print(f"{url1} 和 {url2} 重复")
  62. else:
  63. print("\n没有发现重复节点")