Ping Sweeper是一种网络扫描工具,用于快速检测指定IP范围内哪些主机处于活动状态。它通过发送ICMP回显请求(Ping)并等待响应来实现这一功能。
import os
import platform
def ping(host):
param = '-n 1' if platform.system().lower()=='windows' else '-c 1'
command = f'ping {param} {host}'
response = os.system(command)
return response == 0
import ipaddress
def generate_ip_range(start_ip, end_ip):
start = ipaddress.IPv4Address(start_ip)
end = ipaddress.IPv4Address(end_ip)
return [str(ipaddress.IPv4Address(ip)) for ip in range(int(start), int(end)+1)]
import concurrent.futures
def sweep_network(ip_list, max_threads=50):
active_hosts = []
with concurrent.futures.ThreadPoolExecutor(max_workers=max_threads) as executor:
future_to_ip = {executor.submit(ping, ip): ip for ip in ip_list}
for future in concurrent.futures.as_completed(future_to_ip):
ip = future_to_ip[future]
try:
if future.result():
active_hosts.append(ip)
except Exception as exc:
print(f'{ip} generated an exception: {exc}')
return active_hosts
import os
import platform
import ipaddress
import concurrent.futures
from datetime import datetime
def main():
print("Python Ping Sweeper v1.0")
network = input("输入网络地址(如192.168.1.0/24): ")
try:
ip_list = [str(host) for host in ipaddress.IPv4Network(network)]
except Exception as e:
print(f"无效的网络地址: {e}")
return
print(f"开始扫描 {len(ip_list)} 个IP...")
start_time = datetime.now()
active_hosts = sweep_network(ip_list)
duration = datetime.now() - start_time
print(f"\n扫描完成! 耗时: {duration.total_seconds():.2f}秒")
print(f"活动主机({len(active_hosts)}个):")
for host in active_hosts:
print(f" - {host}")
if __name__ == "__main__":
main()
A: 可能原因包括:主机配置了防火墙阻止ICMP、网络设备过滤了Ping请求、主机确实离线等。
A: 可以增加线程数,但要注意不要过度占用网络资源。通常50-100个线程是比较合理的设置。
A: 仅在你拥有权限的网络中使用此工具。未经授权扫描他人网络可能违反法律。