區域網 DHCP 動態分配 IP,需快速發現哪些 IP 正在使用。多線程並發 Ping 可大幅縮短掃描時間。
import platform
import os
import threading
import time
import sys
def get_ping_param():
"""返回系統對應的 ping 計數參數"""
return '-n' if platform.system().lower() == 'windows' else '-c'
def ping_ip(ip, results, lock):
param = get_ping_param()
# 發送 1 個封包,超時 1 秒
cmd = f"ping {param} 1 -W 1 {ip}"
# Windows 無 -W,改用 -w 毫秒
if platform.system().lower() == 'windows':
cmd = f"ping {param} 1 -w 1000 {ip}"
ret = os.system(cmd)
if ret == 0:
with lock:
results.append(ip)
def scan_network(prefix, max_threads=50):
"""掃描 prefix.1 ~ prefix.255"""
results = []
lock = threading.Lock()
threads = []
for i in range(1, 256):
ip = f"{prefix}.{i}"
t = threading.Thread(target=ping_ip, args=(ip, results, lock))
threads.append(t)
t.start()
# 控制併發數
if len(threads) >= max_threads:
for t in threads:
t.join()
threads = []
# 等待剩餘線程
for t in threads:
t.join()
return sorted(results, key=lambda x: int(x.split('.')[-1]))
if __name__ == '__main__':
if len(sys.argv) < 2:
print("用法: python ip_scan.py 192.168.1")
sys.exit(1)
prefix = '.'.join(sys.argv[1].split('.')[:3])
print(f"掃描 {prefix}.1-255 ...")
start = time.time()
alive = scan_network(prefix)
print(f"存活主機 ({len(alive)}):")
for ip in alive:
print(f" {ip}")
print(f"耗時: {time.time()-start:.1f} 秒")
os.system 同步阻塞,改用 subprocess.run 或 asyncio 可進一步提升效能。cap_net_raw;Windows 一般無需特權。arp-scan 或 scapy 發送 ARP 請求,比 Ping 更快且不受防火牆阻擋。
from scapy.all import ARP, Ether, srp
def arp_scan(network_cidr):
"""發送 ARP 請求掃描存活主機"""
arp = ARP(pdst=network_cidr)
ether = Ether(dst="ff:ff:ff:ff:ff:ff")
packet = ether/arp
result = srp(packet, timeout=2, verbose=0)[0]
return [{"ip": r.psrc, "mac": r.hwsrc} for s, r in result]
# 掃描 192.168.1.0/24
hosts = arp_scan("192.168.1.0/24")
for h in hosts:
print(f"{h['ip']} - {h['mac']}")
scapy 需安裝 (pip install scapy) 且 Linux 需 root,但速度極快且可獲取 MAC 位址。