萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python 掃描區域網存活主機:多線程 Ping 掃描器

需求背景

區域網 DHCP 動態分配 IP,需快速發現哪些 IP 正在使用。多線程並發 Ping 可大幅縮短掃描時間。

跨平台 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} 秒")

關鍵優化點

  • 線程池控制:限制同時線程數(如 50),避免建立過多線程導致系統負載過高。
  • 非阻塞 Ping:os.system 同步阻塞,改用 subprocess.run 或 asyncio 可進一步提升效能。
  • ICMP 權限:Linux 需 root 權限或設定 cap_net_raw;Windows 一般無需特權。
  • ARP 掃描替代:同網段可用 arp-scan 或 scapy 發送 ARP 請求,比 Ping 更快且不受防火牆阻擋。

Scapy 版本(更專業)


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 位址。

copyright © 萬盛學電腦網 all rights reserved