批量检测局域网连通性

批量检测局域网连通性

管理员
2025-03-04 / 0 评论 / 34 阅读 / 正在检测是否收录...
import subprocess
import ipaddress
import platform
from concurrent.futures import ThreadPoolExecutor

def generate_ips():
    """生成192.168.17.1-192.168.17.254的IP列表"""
    network = ipaddress.IPv4Network("192.168.17.0/24")
    return [str(host) for host in network.hosts()]  # 自动排除.0和.255‌:ml-citation{ref="1,3" data="citationList"}

def check_ping(ip, timeout=1):
    """检测IP是否可达"""
    param = "-n" if platform.system().lower() == "windows" else "-c"
    command = ["ping", param, "1", "-w", str(timeout), ip]
    try:
        response = subprocess.run(
            command, stdout=subprocess.PIPE,
            stderr=subprocess.PIPE, timeout=timeout
        )
        return ip, response.returncode == 0
    except:
        return ip, False

def main():
    ips = generate_ips()
    reachable = []
    unreachable = []

    with ThreadPoolExecutor(max_workers=50) as executor:
        results = executor.map(check_ping, ips)
        for ip, status in results:
            if status:
                reachable.append(ip)
                print(f"\033[92m✅ {ip} 可达\033[0m")
            else:
                unreachable.append(ip)
                print(f"\033[91m❌ {ip} 不可达\033[0m")

    print(f"\n\033[1m统计结果:\033[0m")
    print(f"可达IP数:{len(reachable)},示例:{reachable[:3]}...")
    print(f"不可达IP数:{len(unreachable)},示例:{unreachable[:3]}...")

if __name__ == "__main__":
    main()
2

评论 (0)

取消