python扫描某个网段下活跃设备,ping包需要安装一下,下面有命令,安装完成后copy代码就可以运行起来了
pip install ping3
from ping3 import ping, verbose_ping
def is_host_alive(ip_address, timeout=1):
"""Check if a host is alive by sending an ICMP ECHO_REQUEST."""
return ping(ip_address, timeout=timeout)
def scan_network(network_prefix, start_range, end_range):
"""Scan a network range and return the active hosts."""
active_hosts = []
for i in range(start_range, end_range + 1):
ip_address = f"{network_prefix}.{i}"
print("正在扫描:",ip_address)
if is_host_alive(ip_address):
active_hosts.append(ip_address)
print("该IP活跃【",ip_address,"】\n")
return active_hosts
if __name__ == "__main__":
network_prefix = '192.168.1' # Replace with your network prefix
start_range = 1
end_range = 254
active_devices = scan_network(network_prefix, start_range, end_range)
print(f"Active devices: {active_devices}")