#!/usr/bin/env python # -*- coding: utf-8 -*- import subprocess import ipaddress def ping_ip(ip, count=3): """Ping an IP address using the system's ping command with a given count.""" # 构造ping命令 param = ['ping', '-c', str(count), ip] # 执行ping命令 response = subprocess.run(param, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) # 检查ping是否成功 if response.returncode == 0: return True else: return False def find_unused_ips(network, prefix_len=24, ping_count=3): """Find unused IPs in a given network.""" net = ipaddress.ip_network(f"{network}/{prefix_len}", strict=False) unused_ips = [] # 跳过.1(通常是网关)和.255(广播地址) for host in net.hosts(): if host.is_private and not (host.exploded[-1] == '1' or host.exploded[-1] == '255'): if not ping_ip(str(host), ping_count): unused_ips.append(str(host)) return unused_ips # 假设我们要扫描的网段是192.168.21.x network = '192.168.21.0' unused_ips = find_unused_ips(network) print("Unused IPs in the network:", unused_ips)
标签:网段,network,ip,ping,unused,ips,host,内网 From: https://www.cnblogs.com/music-liang/p/18315648