扫描局域网内所有IP&主机名
code(python)
Pythonimport os
import sys
import socket
import threading
import time
from datetime import datetime
class LanScanner:
def __init__(self):
self.active_hosts = []
self.lock = threading.Lock()
self.stop_event = threading.Event()
self.max_threads = 5 # 大幅降低并发数,适合Win7
def get_local_ip(self):
"""获取本地IP(简化版,不依赖netifaces)"""
try:
# 创建临时socket获取本地IP
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
local_ip = s.getsockname()[0]
s.close()
return local_ip
except:
return "192.168.1.1" # 默认本地IP
def get_subnet(self, local_ip):
"""从本地IP生成子网(简化逻辑)"""
return ".".join(local_ip.split(".")[:3]) + ".0/24"
def ping_host(self, ip):
"""Ping主机(优化超时和参数)"""
if self.stop_event.is_set():
return False
try:
param = '-n 1 -w 500' if sys.platform == 'win32' else '-c 1 -W 1'
# 直接在命令中重定向输出,避免弹窗
response = os.system(f"ping {param} {ip} > NUL 2>&1")
return response == 0
except:
return False
def get_hostname(self, ip):
"""获取主机名(增加超时控制)"""
try:
socket.setdefaulttimeout(2) # 缩短超时
hostname, _, _ = socket.gethostbyaddr(ip)
return hostname
except:
return "未知主机名"
def scan_ip(self, ip):
"""扫描单个IP"""
if self.ping_host(ip):
hostname = self.get_hostname(ip)
with self.lock:
self.active_hosts.append((ip, hostname))
print(f"发现: {ip} - {hostname}")
def scan_subnet(self, subnet):
"""扫描子网(优化线程管理)"""
try:
network = subnet.split('/')[0]
base_ip = ".".join(network.split(".")[:3])
start = 1
end = 254 # 扫描1-254段
print(f"开始扫描 {base_ip}.{start}-{end},请稍候...")
start_time = datetime.now()
threads = []
for i in range(start, end + 1):
if self.stop_event.is_set():
break
ip = f"{base_ip}.{i}"
# 控制线程数量,避免过多
while len(threads) >= self.max_threads:
threads = [t for t in threads if t.is_alive()]
time.sleep(0.1) # 稍等再检查
# 创建并启动线程
thread = threading.Thread(target=self.scan_ip, args=(ip,))
threads.append(thread)
thread.start()
# 等待剩余线程结束
for thread in threads:
if thread.is_alive():
thread.join()
duration = datetime.now() - start_time
print(f"\n扫描完成,耗时 {duration.total_seconds():.2f} 秒")
print(f"共发现 {len(self.active_hosts)} 个活跃主机")
except Exception as e:
print(f"扫描出错: {e}")
def start_scan(self):
"""开始扫描"""
local_ip = self.get_local_ip()
subnet = self.get_subnet(local_ip)
print(f"本地IP: {local_ip}")
print(f"扫描范围: {subnet}")
print("按Ctrl+C停止扫描")
try:
self.scan_subnet(subnet)
return self.active_hosts
except KeyboardInterrupt:
print("\n用户中断扫描")
self.stop_event.set()
return self.active_hosts
if __name__ == "__main__":
print("=== 局域网扫描工具(Win7兼容版)===")
scanner = LanScanner()
hosts = scanner.start_scan()
if hosts:
print("\n=== 结果 ===")
for ip, hostname in sorted(hosts, key=lambda x: x[0]):
print(f"{ip}\t{hostname}")
机房扫描结果
代码================= RESTART: C:/Users/Administrator/Desktop/1.py =================
=== 局域网扫描工具(Win7兼容版)===
本地IP: 192.168.40.7
扫描范围: 192.168.40.0/24
按Ctrl+C停止扫描
开始扫描 192.168.40.1-254,请稍候...
发现: 192.168.40.7 - S68
发现: 192.168.40.2 - S66
发现: 192.168.40.4 - S58
发现: 192.168.40.1 - S44
发现: 192.168.40.3 - S34
发现: 192.168.40.8 - S65
发现: 192.168.40.11 - S45
发现: 192.168.40.10 - S24
发现: 192.168.40.12 - S17
发现: 192.168.40.13 - S41
发现: 192.168.40.14 - S57
发现: 192.168.40.15 - S46
发现: 192.168.40.19 - S21
发现: 192.168.40.20 - S14
发现: 192.168.40.21 - S27
发现: 192.168.40.26 - S25
发现: 192.168.40.27 - S23
发现: 192.168.40.28 - S26
发现: 192.168.40.29 - S33
发现: 192.168.40.30 - S42
发现: 192.168.40.31 - S32
发现: 192.168.40.32 - S54
发现: 192.168.40.33 - S52
发现: 192.168.40.34 - S53
发现: 192.168.40.35 - S11
发现: 192.168.40.37 - S48
发现: 192.168.40.38 - S51
发现: 192.168.40.39 - S67
发现: 192.168.40.40 - S35
发现: 192.168.40.44 - S55
发现: 192.168.40.45 - S47
发现: 192.168.40.46 - S13
发现: 192.168.40.48 - S36
发现: 192.168.40.50 - S22
发现: 192.168.40.53 - S56
发现: 192.168.40.54 - S28
发现: 192.168.40.55 - S16
发现: 192.168.40.58 - S38
发现: 192.168.40.59 - S37
发现: 192.168.40.60 - DESKTOP-U5CI7B4
发现: 192.168.40.61 - S15
发现: 192.168.40.254 - 未知主机名
扫描完成,耗时 140.36 秒
共发现 42 个活跃主机
=== 结果 ===
192.168.40.1 S44
192.168.40.10 S24
192.168.40.11 S45
192.168.40.12 S17
192.168.40.13 S41
192.168.40.14 S57
192.168.40.15 S46
192.168.40.19 S21
192.168.40.2 S66
192.168.40.20 S14
192.168.40.21 S27
192.168.40.254 未知主机名
192.168.40.26 S25
192.168.40.27 S23
192.168.40.28 S26
192.168.40.29 S33
192.168.40.3 S34
192.168.40.30 S42
192.168.40.31 S32
192.168.40.32 S54
192.168.40.33 S52
192.168.40.34 S53
192.168.40.35 S11
192.168.40.37 S48
192.168.40.38 S51
192.168.40.39 S67
192.168.40.4 S58
192.168.40.40 S35
192.168.40.44 S55
192.168.40.45 S47
192.168.40.46 S13
192.168.40.48 S36
192.168.40.50 S22
192.168.40.53 S56
192.168.40.54 S28
192.168.40.55 S16
192.168.40.58 S38
192.168.40.59 S37
192.168.40.60 DESKTOP-U5CI7B4
192.168.40.61 S15
192.168.40.7 S68
192.168.40.8 S65