内网ip扫描—终章

dfnb12369个月前132

在鸽了将近两个月之后,我终于用python写了个内网脚本出来,接下来我应该会把她开源到github上OvO

import os
import platform
import ipaddress
import argparse
import subprocess
from concurrent.futures import ThreadPoolExecutor, as_completed

SYSTEM = platform.system().lower()

# ---------- 1. ping ----------
def build_ping_cmd(host: str, timeout_ms: int) -> str:
    if SYSTEM == "windows":
        return f"ping -n 1 -w {timeout_ms} {host} >NUL 2>&1"
    else:
        timeout_s = max(1, timeout_ms // 1000)
        return f"ping -c 1 -W {timeout_s} {host} >/dev/null 2>&1"

def ping_host(host: str, timeout_ms: int) -> bool:
    return os.system(build_ping_cmd(host, timeout_ms)) == 0

# ---------- 2. 名称解析 ----------
def get_name(host: str) -> str:
    """
    先尝试 nslookup,再尝试 nbtstat(Windows)或 smbclient(Linux)
    返回解析到的第一个名字,失败则返回空串
    """
    # 1. nslookup
    try:
        out = subprocess.check_output(
            ["nslookup", host], timeout=3, stderr=subprocess.DEVNULL
        ).decode(errors="ignore")
        for line in out.splitlines():
            line = line.strip()
            if line.lower().startswith("name:"):
                return line.split()[1].rstrip(".")
    except Exception:
        pass

    # 2. Windows 专用 nbtstat
    if SYSTEM == "windows":
        try:
            out = subprocess.check_output(
                ["nbtstat", "-A", host], timeout=3, stderr=subprocess.DEVNULL
            ).decode(errors="ignore")
            for line in out.splitlines():
                line = line.strip()
                if "<00>" in line and "UNIQUE" in line:
                    return line.split()[0]
        except Exception:
            pass
    return ""

# ---------- 3. 扫描 ----------
def sweep(network: str, timeout_ms: int, workers: int):
    try:
        net = ipaddress.ip_network(network, strict=False)
    except ValueError as e:
        print("网段格式错误:", e)
        exit(1)

    alive = []
    print(f"开始扫描 {network},并发:{workers},超时:{timeout_ms} ms\n")
    with ThreadPoolExecutor(max_workers=workers) as pool:
        future_map = {pool.submit(ping_host, str(ip), timeout_ms): ip for ip in net.hosts()}
        for f in as_completed(future_map):
            ip = str(future_map[f])
            if f.result():
                name = get_name(ip)
                alive.append((ip, name))
                print(f"[+] {ip:<15}  {name or '--'}")
    print(f"\n扫描完成,存活 {len(alive)} 台:")
    for ip, name in alive:
        print(f"{ip:<15}  {name or '--'}")
    return alive

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="网段存活扫描 + 设备名称")
    parser.add_argument("network", help="例:192.168.1.0/24")
    parser.add_argument("-w", "--timeout", type=int, default=500, help="ping 超时毫秒,默认 500")
    parser.add_argument("-c", "--concurrency", type=int, default=100, help="并发数,默认 100")
    args = parser.parse_args()
    sweep(args.network, args.timeout, args.concurrency)

使用方法是:

python 脚本名.py 网段/24 -w 最大毫秒数 -c 线程

比如:

python sweep_with_name.py 192.168.1.0/24 -w 600 -c 50


博客网址:blog.5948888.xyz

B站:此生只为芭芭拉

未经允许请勿转载

相关文章

都5202年啦,你还在用windows?(差异篇)

都5202年啦,你还在用windows?(差异篇)

距离上一篇博文已经过了差不多两个月了,很不幸月更目前看来因该是失败了捏,那么我们这一篇博文就来谈一谈操作系统8 OvO知周所众 windous10 因为巨硬微软的调整正式的完成了她的生命周期,也就是说...

g102鼠标回滚换编码器教程

g102鼠标回滚换编码器教程

AUV您吉祥,咱们也是赶上了罗技的计划性报废,在过保的3个月后出现了鼠标回滚:(但是其实也非常好解决,只需要换一个编码器就好了,那么您需要准备电烙铁和电子钳这两样工具并且撕下来圈出来的三个脚贴和贴纸,...

凤凰205—最适合小白玩胶片的机器

凤凰205—最适合小白玩胶片的机器

距离我的上一篇博文已经差不多过去了4个月了在这段时间里我稍微有点沉迷摄影也就有了这一片博文,也就是我的第一台胶片机也是我的第一台相机凤凰205d或许各位同志们会疑惑?不是说推荐205吗那后面的D是什么...

免费搭建你自己的ChatGPT—白嫖雨云虚拟主机

免费搭建你自己的ChatGPT—白嫖雨云虚拟主机

Hi,大家好我是芭芭拉经过上期的教程大家应该已经成功的部署了一个个人博客那么今天我就教大家如何白嫖雨云虚拟主机并且利用&#34;dirk1983&#34;大佬的PHP-chatgpt项...

白嫖!!!免费二级域名可托管到CF

白嫖!!!免费二级域名可托管到CF

本来说是要把带英游记写完的,但是没崩住把扫描仪卖了,这段时间也比较的忙就只能搁置一手啦QAQ那么我们这篇博文就来填白嫖二级域名的坑-----------------------------------...

国产神机—DF300xd

国产神机—DF300xd

因为目前胶卷还没有扫描完的原因带英游记的第二篇可能要等到9月中旬了博客欠的文章也尽量在今年补完-----------------------------------------------------...

发表评论    

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。