network.py 946 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. """
  2. 网络工具模块
  3. """
  4. import subprocess
  5. from utils.logger import logger
  6. from typing import Optional
  7. def ping_host(host: str) -> bool:
  8. """
  9. 检测主机连通性
  10. Args:
  11. host: 目标主机IP
  12. Returns:
  13. bool: 是否可达
  14. """
  15. try:
  16. response = subprocess.run(
  17. ["ping", "-c", "1", host],
  18. stdout=subprocess.PIPE,
  19. stderr=subprocess.PIPE,
  20. timeout=5
  21. )
  22. return response.returncode == 0
  23. except (subprocess.TimeoutExpired, FileNotFoundError, Exception) as e:
  24. logger.error(f"Ping检测失败: {e}")
  25. return False
  26. def check_network_connectivity(host: str) -> Optional[str]:
  27. """
  28. 检查网络连接状态
  29. Args:
  30. host: 目标主机
  31. Returns:
  32. str: 连接状态描述,失败时返回None
  33. """
  34. if ping_host(host):
  35. return f"网络连接正常: {host}"
  36. else:
  37. return None