跳到正文

个人记录

一些代码

wujiawei36约 7 分钟
原文

这是 2025年11月5日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年5月6日
篇幅
约 7 分钟

版本

  1. v2当前
  2. v1

扫描局域网内所有IP&主机名

Python
import 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}")