Files

77 lines
3.1 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# windiscover — Windows 主机名自动发现
在 Linux 上自动发现局域网内 Windows 主机的 **NetBIOS 主机名**,并维护
`/etc/hosts` 中的托管区块,使 `ping win-pc`、`smb://win-pc/share`、`ssh win-pc`
等可以直接使用主机名,无需手工维护 hosts。
需要 Linux + systemd、Python 3.8+、iproute2(`ip` 命令)和 root 权限。
## 安装
```bash
sudo bash install.sh
```
安装后会立即执行一次扫描,并启用一个 systemd 定时器,之后每 5 分钟自动刷新。
## 日常使用
```bash
windiscover # 扫描并显示发现的主机
windiscover --no-sweep # 快速模式(广播 + ARP 邻居 + 已知主机)
windiscover --json # JSON 输出
sudo windiscover --update-hosts # 扫描并更新 /etc/hosts
sudo windiscover --sweep-all --update-hosts # 全量扫描本机所有 IPv4 网段
sudo windiscover --remove # 只删除 /etc/hosts 中的托管区块
```
安装后的文件:
| 路径 | 用途 |
| --- | --- |
| `/usr/local/sbin/windiscover` | 扫描程序 |
| `/etc/systemd/system/windows-name-discovery.service` | 单次扫描服务 |
| `/etc/systemd/system/windows-name-discovery.timer` | 每 5 分钟触发 |
| `/var/lib/windiscover/state.json` | 已发现主机状态(含未响应计数) |
| `/etc/hosts` | 自动维护的托管区块 |
## 工作原理
1. 向本机各 IPv4 网段的广播地址发送 NetBIOS 节点状态查询(NBSTAT,UDP/137);
2. 扫描默认网关所在 `/24`,并每次轮换一个本地 `/24`(约 40 分钟覆盖全部网段);
3. 查询 ARP 邻居表和上次已发现的主机(即使它们暂时从 ARP 表消失);
4. 解析应答中的唯一 `<00>` NetBIOS 名称、工作组和 MAC;
5. 写入 `/etc/hosts` 的托管区块:
```text
# BEGIN windows-name-discovery (managed automatically, do not edit)
192.0.2.10 win-pc
...
# END windows-name-discovery
```
主机偶尔一次没响应不会被删除;状态文件记录未响应次数,默认连续 6 次
(主网段约 30 分钟)无响应才清除。手动写在托管区块之外的 hosts 条目优先,
脚本不会覆盖同名记录。
## 限制与注意
- 仅支持 IPv4 和 NetBIOS。关闭了 NetBIOS 名称服务、仅依赖 LLMNR/mDNS 的
Windows 主机无法通过此方式发现。
- NetBIOS 应答没有认证,局域网内任何主机都能伪造应答。请只在可信局域网
中使用;本工具只采集名称和地址,不会执行应答内容,但解析结果仍可能被投毒。
- 不修改 `nsswitch.conf` 或 DNS 配置,依赖 `hosts: files ...` 中 `files` 优先
(Ubuntu 默认即如此)。
- 定时扫描会产生少量 UDP/137 和 ARP 流量,默认每次扫描两个 `/24`。
- 需要 root 权限才能更新 `/etc/hosts` 和绑定 137 端口;非 root 运行时自动
改用临时端口,只读显示结果。
## 卸载
```bash
sudo bash uninstall.sh
```
会停止并删除 systemd 单元、程序、状态文件,以及 `/etc/hosts` 中的托管区块;
`/etc/hosts` 的其它内容不受影响。