72 lines
2.4 KiB
Bash
72 lines
2.4 KiB
Bash
#!/usr/bin/env bash
|
||||
|
|
# 安装并启用 Windows/NetBIOS 主机名自动发现
|
|||
|
|
set -euo pipefail
|
|||
|
|
|
|||
|
|
if [[ ${EUID:-$(id -u)} -ne 0 ]]; then
|
|||
|
|
echo "请使用 sudo 运行: sudo bash \"$0\"" >&2
|
|||
|
|
exit 1
|
|||
|
|
fi
|
|||
|
|
|
|||
|
|
if [[ ! -x /usr/bin/python3 ]]; then
|
|||
|
|
echo "错误: 需要 /usr/bin/python3" >&2
|
|||
|
|
exit 1
|
|||
|
|
fi
|
|||
|
|
if ! /usr/bin/python3 -c 'import sys; raise SystemExit(0 if sys.version_info >= (3, 8) else 1)'; then
|
|||
|
|
echo "错误: 需要 Python 3.8 或更高版本(/usr/bin/python3)" >&2
|
|||
|
|
exit 1
|
|||
|
|
fi
|
|||
|
|
for cmd in install systemctl ip readlink; do
|
|||
|
|
if ! command -v "$cmd" >/dev/null 2>&1; then
|
|||
|
|
echo "错误: 缺少依赖 $cmd" >&2
|
|||
|
|
exit 1
|
|||
|
|
fi
|
|||
|
|
done
|
|||
|
|
|
|||
|
|
here="$(cd "$(dirname "$(readlink -f "$0")")" && pwd)"
|
|||
|
|
|
|||
|
|
install -d -m 0755 /usr/local/sbin
|
|||
|
|
install -d -m 0755 /usr/local/share/doc/windiscover
|
|||
|
|
install -d -m 0755 /var/lib/windiscover
|
|||
|
|
install -m 0755 "$here/windiscover" /usr/local/sbin/windiscover
|
|||
|
|
install -m 0644 "$here/README.md" /usr/local/share/doc/windiscover/README.md
|
|||
|
|
install -m 0644 "$here/windows-name-discovery.service" \
|
|||
|
|
/etc/systemd/system/windows-name-discovery.service
|
|||
|
|
install -m 0644 "$here/windows-name-discovery.timer" \
|
|||
|
|
/etc/systemd/system/windows-name-discovery.timer
|
|||
|
|
|
|||
|
|
systemctl daemon-reload
|
|||
|
|
systemctl enable --now windows-name-discovery.timer
|
|||
|
|
|
|||
|
|
echo "正在执行首次扫描(约 10 秒)..."
|
|||
|
|
systemctl start windows-name-discovery.service || true
|
|||
|
|
systemctl --no-pager --full status windows-name-discovery.service || true
|
|||
|
|
|
|||
|
|
echo
|
|||
|
|
echo "===== /etc/hosts 中自动维护的记录 ====="
|
|||
|
|
awk '/^# BEGIN windows-name-discovery/{show=1; next} /^# END windows-name-discovery/{show=0} show {print}' \
|
|||
|
|
/etc/hosts || true
|
|||
|
|
|
|||
|
|
echo
|
|||
|
|
echo "===== 解析验证 ====="
|
|||
|
|
mapfile -t names < <(
|
|||
|
|
awk '/^# BEGIN windows-name-discovery/{show=1; next}
|
|||
|
|
/^# END windows-name-discovery/{show=0}
|
|||
|
|
show {print $2}' /etc/hosts
|
|||
|
|
)
|
|||
|
|
if [[ ${#names[@]} -eq 0 ]]; then
|
|||
|
|
echo "尚未发现主机(局域网内可能没有开启 NetBIOS 名称服务的 Windows 主机)。"
|
|||
|
|
else
|
|||
|
|
for name in "${names[@]:0:5}"; do
|
|||
|
|
getent hosts "$name" || echo "$name 解析失败"
|
|||
|
|
done
|
|||
|
|
if [[ ${#names[@]} -gt 5 ]]; then
|
|||
|
|
echo "... 共 ${#names[@]} 条,完整列表请运行: windiscover"
|
|||
|
|
fi
|
|||
|
|
fi
|
|||
|
|
|
|||
|
|
echo
|
|||
|
|
systemctl list-timers windows-name-discovery.timer --no-pager || true
|
|||
|
|
echo
|
|||
|
|
echo "安装完成。之后每 5 分钟自动扫描一次。"
|
|||
|
|
echo "手动查看: windiscover"
|
|||
|
|
echo "手动全量刷新: sudo windiscover --sweep-all --update-hosts"
|