内网ip扫描—终章
在鸽了将近两个月之后,我终于用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站:此生只为芭芭拉
未经允许请勿转载





