添加windows主机名发现和按需挂载共享工具.

This commit is contained in:
tsf committed 2026-11-06 11:41:59 +08:00
commit d7b8a21ca5
12 files changed
+2119

No files matched your search

+13
View File
@@ -0,0 +1,13 @@
# Credentials / runtime state (never commit)
*.cred
winshare.conf
state.json
*.log
# Python
__pycache__/
*.py[cod]
# OS / editor
.DS_Store
*.swp
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Tan Shifeng
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+95
View File
@@ -0,0 +1,95 @@
# tools-linux
Linux 局域网小工具集,当前包含两个与 Windows 互通相关的工具。
> Linux utilities for Windows hostname discovery and SMB share automounting.
仅建议在可信局域网中使用。
## 工具
| 工具 | 作用 | 文档 |
| --- | --- | --- |
| [windiscover](windiscover/) | 通过 NetBIOS 自动发现 Windows 主机名,维护 `/etc/hosts` | [README](windiscover/README.md) |
| [winshare](winshare/) | 通过 CIFS + systemd automount 按需挂载 Windows SMB 共享 | [README](winshare/README.md) |
## 环境要求
- Linux + systemd
- Python 3.8+(windiscover;winshare 的卸载脚本也需要 python3)
- bash、iproute2、util-linux(`mountpoint`、`findmnt`)
- `cifs-utils`:Debian/Ubuntu 系由 winshare 自动安装;其他发行版请预先安装
- root 权限(systemd、`/etc/hosts`、`/etc/fstab`、SMB 凭据文件)
在 Ubuntu 26.04 上测试。
## 快速开始
### Windows 主机名自动发现
```bash
cd windiscover
sudo bash install.sh
windiscover # 查看发现的主机
```
安装后 systemd timer 每 5 分钟更新 `/etc/hosts` 中的托管区块。支持
`windiscover`、`sudo windiscover --sweep-all --update-hosts`、
`sudo windiscover --remove` 等命令。
### Windows 共享按需自动挂载
```bash
cd winshare
sudo bash setup-winshare.sh
```
按提示输入 Windows 主机、共享名、挂载点和账号密码。默认访问挂载点时自动
挂载,空闲 10 分钟自动卸载。
## 卸载
```bash
cd windiscover && sudo bash uninstall.sh
cd winshare && sudo bash remove-winshare.sh
```
## 工作原理
- **windiscover**:向本机各 IPv4 网段的广播地址、主 `/24`、轮换本地 `/24`
以及 ARP 邻居发送 NetBIOS 节点状态查询(NBSTAT,UDP/137),解析 `<00>`
名称后写入 `/etc/hosts` 的托管区块,并用 systemd timer 定期刷新。
- **winshare**:交互式生成 SMB 凭据文件(0600,root)和 `/etc/fstab` 条目,
通过 `x-systemd.automount` 实现按需挂载;卸载脚本负责清理配置。
## 安全说明
- NetBIOS 名称应答没有认证,局域网内任何主机都可以伪造应答(名称投毒)。
windiscover 只采集名称和地址,不执行应答内容,但仍建议只在可信局域网使用。
- winshare 的 SMB 密码保存在 `/etc/samba/credentials/` 下(0600,root),
`/etc/fstab` 只引用凭据文件路径,不包含密码。
- windiscover 只修改 `/etc/hosts` 中带标记的托管区块;卸载时只删除该区块。
- 两个工具都会修改系统配置,请先阅读脚本再执行。
## 目录结构
```text
tools-linux/
├── windiscover/
│ ├── windiscover
│ ├── windows-name-discovery.service
│ ├── windows-name-discovery.timer
│ ├── install.sh
│ ├── uninstall.sh
│ └── README.md
└── winshare/
├── setup-winshare.sh
├── remove-winshare.sh
└── README.md
```
## License
本项目采用 [MIT License](LICENSE)。
Copyright (c) 2026 Tan Shifeng
+76
View File
@@ -0,0 +1,76 @@
# 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` 的其它内容不受影响。
+72
View File
@@ -0,0 +1,72 @@
#!/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"
+43
View File
@@ -0,0 +1,43 @@
#!/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
systemctl disable --now windows-name-discovery.timer 2>/dev/null || true
systemctl stop windows-name-discovery.service 2>/dev/null || true
if [[ -x /usr/local/sbin/windiscover ]]; then
if ! /usr/local/sbin/windiscover --remove; then
echo "错误: 未能删除 /etc/hosts 中的托管区块,已停止卸载。" >&2
echo "请检查 /etc/hosts 中的 windows-name-discovery 标记后重试。" >&2
exit 1
fi
else
echo "警告: 未找到 /usr/local/sbin/windiscover,无法自动清理 /etc/hosts。" >&2
echo "请手动检查并删除其中的 windows-name-discovery 托管区块。" >&2
fi
if [[ -f /etc/hosts ]] && grep -q '^# BEGIN windows-name-discovery' /etc/hosts; then
echo "错误: /etc/hosts 中仍有 windows-name-discovery 托管区块,已停止卸载。" >&2
echo "请先手动删除该区块,或修复标记后重新运行卸载脚本。" >&2
exit 1
fi
rm -f /usr/local/sbin/windiscover
rm -f /etc/systemd/system/windows-name-discovery.service
rm -f /etc/systemd/system/windows-name-discovery.timer
systemctl daemon-reload
# 只删除本工具生成的文件,保留目录中的其它内容
rm -f /var/lib/windiscover/state.json
rmdir /var/lib/windiscover 2>/dev/null || true
rm -f /usr/local/share/doc/windiscover/README.md
rmdir /usr/local/share/doc/windiscover 2>/dev/null || true
rm -f /run/lock/windiscover.lock
echo "已卸载 windiscover 程序和 systemd 单元。"
echo "/etc/hosts 的托管区块已在可用时清理;如有警告请手动检查。"
+1085
View File
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,15 @@
[Unit]
Description=Discover Windows/NetBIOS hostnames and update /etc/hosts
Documentation=file:///usr/local/share/doc/windiscover/README.md
Wants=network-online.target
After=network-online.target
[Service]
Type=oneshot
ExecStart=/usr/bin/python3 -I /usr/local/sbin/windiscover --update-hosts --quiet
Nice=10
IOSchedulingClass=idle
PrivateTmp=yes
ProtectHome=yes
ProtectSystem=true
NoNewPrivileges=yes
+12
View File
@@ -0,0 +1,12 @@
[Unit]
Description=Periodically discover Windows/NetBIOS hostnames
[Timer]
OnBootSec=30s
OnUnitActiveSec=5min
AccuracySec=30s
RandomizedDelaySec=15s
Persistent=false
[Install]
WantedBy=timers.target
+95
View File
@@ -0,0 +1,95 @@
# winshare — Windows SMB 共享按需自动挂载
使用 `cifs-utils` + systemd automount 把 Windows 共享按需挂载到 Linux:
- 访问挂载点时自动挂载,空闲 10 分钟自动卸载;
- Windows 关机或离线不会阻塞开机;
- 密码保存在仅 root 可读的凭据文件中,不写入 fstab。
## 安装
在**普通终端窗口**运行(脚本需要隐藏读取密码,必须能访问 TTY):
```bash
sudo bash setup-winshare.sh
```
脚本会依次询问:
1. **Windows 主机名或 IP**(例如 `win-pc` 或 `192.0.2.10`)
2. **共享名**(Windows 上运行 `net share` 或 PowerShell `Get-SmbShare` 可查看)
3. **Linux 挂载点**(默认 `/mnt/windows-<共享名小写>`)
4. **Windows 用户名**
- 本地账号:`alice` 或 `WINDOWS-HOST\alice`
- 微软账号:`MicrosoftAccount\you@example.com`
- 域账号:`DOMAIN\user`
- Windows 的 cmd 中运行 `whoami` 可看到准确格式
5. **域/工作组**:默认是 Windows 计算机名;输入 `-` 表示不指定
6. **密码**:输入两次,终端不回显
也可以用环境变量预填主机、共享名和挂载点:
```bash
sudo env HOST=win-pc SHARE=ShareName MOUNT=/mnt/share bash setup-winshare.sh
```
之后脚本会安装 `cifs-utils`(仅 apt 系;其他发行版请先手动安装),实际测试
挂载,写入 `/etc/fstab`,配置 systemd automount 并验证。需要 systemd、
util-linux(`mountpoint`、`findmnt`)和 root 权限;卸载脚本还需要 python3。
## 访问
```bash
ls -la /mnt/share
```
第一次访问触发挂载,之后空闲 10 分钟自动卸载;再次访问会自动挂载。
## 管理
```bash
findmnt /mnt/share
sudo umount /mnt/share
unit="$(systemd-escape -p --suffix=mount /mnt/share)"
journalctl -u "$unit" -n 30 --no-pager
sudo bash remove-winshare.sh
```
配置和凭据位置:
- `/etc/fstab` 中的注释 + 挂载条目
- `/etc/samba/credentials/winshare-<host>-<share>.cred`(0600 root)
- `/etc/winshare.conf`(记录本次配置,供卸载脚本使用)
## 常见问题
| 现象 | 可能原因 / 处理 |
| --- | --- |
| `mount error(2): No such file or directory` | 共享名不对。在 Windows 运行 `net share` 或 PowerShell `Get-SmbShare` 确认 |
| `mount error(13): Permission denied` | 用户名/密码/域错误,或 Windows 共享/NTFS 权限不足 |
| `mount error(112): Host is down` | Windows 主机离线、IP 变化,或防火墙阻止 445 |
| `NT_STATUS_LOGON_FAILURE` | 账号格式不对。试 `WINDOWS-HOST\用户名`、`WORKGROUP`、`MicrosoftAccount\邮箱` |
| 微软账号密码登录失败 | 该账号可能启用了无密码/Windows Hello。建议在 Windows 上新建一个带密码的本地账号专用于共享 |
| 管理共享 `C$`/`D$` 失败 | 管理共享需要管理员账号,且受 UAC 远程限制;建议改用普通共享 |
| SMB 版本不兼容 | 重试:`VERS=2.1`(旧设备)或 `VERS=3.1.1`:`VERS=2.1 sudo bash setup-winshare.sh` |
| Windows 上无法访问 | 网络配置文件设为“专用”,启用“文件和打印机共享”;必要时在防火墙放行 SMB |
| Windows 主机名解析失败 | 本机的 `/etc/hosts` 可由 `windiscover` 维护;也可改用 IP:`HOST=192.0.2.10 sudo bash setup-winshare.sh` |
## 说明
- 挂载归属为执行 sudo 的 Linux 用户(读取 `SUDO_UID`/`SUDO_GID`),文件权限
`0660`、目录权限 `0770`。
- 挂载点必须位于 `/mnt`、`/media`、`/srv` 或 `/home` 下,并且是空目录或不
存在的目录。脚本会拒绝系统目录、符号链接、非空目录,以及已被其它文件系统
占用的挂载点,避免误覆盖或误卸载。
- 实际运行时只写入 `/etc/fstab`、`/etc/samba/credentials` 和
`/etc/winshare*.conf`;测试可用 `DRY_RUN=1` 指定临时路径。
- 如果 Windows 端要求 SMB 加密,可在 `/etc/fstab` 的挂载选项中追加 `seal`,
然后 `sudo systemctl daemon-reload && sudo umount <挂载点>`。
- 默认使用 `x-systemd.automount` 按需挂载;如果希望开机常驻挂载,删除
`x-systemd.automount` 和 `x-systemd.idle-timeout=...`,保留 `_netdev,nofail`。
- 多套共享:用不同的挂载点,并通过 `CONFIG_FILE` 指定不同的配置文件,例如
`CONFIG_FILE=/etc/winshare-work.conf`;卸载时同样指定。
- 共享名不能包含空格或斜杠(fstab 条目会因此变得复杂)。
+210
View File
@@ -0,0 +1,210 @@
#!/usr/bin/env bash
# 移除 setup-winshare.sh 创建的 SMB 自动挂载配置
set -euo pipefail
if [[ ${EUID:-$(id -u)} -ne 0 ]]; then
echo "请使用 sudo 运行: sudo bash \"$0\"" >&2
exit 1
fi
for cmd in systemctl systemd-escape mountpoint findmnt python3 dirname basename readlink awk cp; do
if ! command -v "$cmd" >/dev/null 2>&1; then
echo "错误: 缺少依赖 $cmd" >&2
exit 1
fi
done
CONFIG_FILE="${CONFIG_FILE:-/etc/winshare.conf}"
HOST="${HOST:-}"
SHARE="${SHARE:-}"
MOUNT="${MOUNT:-}"
FSTAB="${FSTAB:-/etc/fstab}"
CRED_FILE="${CRED_FILE:-}"
if [[ -f "$CONFIG_FILE" ]]; then
if [[ "$(dirname "$CONFIG_FILE")" != "/etc" || "$(basename "$CONFIG_FILE")" != winshare*.conf ]]; then
echo "错误: 拒绝读取非 /etc/winshare*.conf 的配置文件: $CONFIG_FILE" >&2
exit 1
fi
# 只解析 KEY=VALUE,不执行配置文件内容
while IFS= read -r line || [[ -n "$line" ]]; do
case "$line" in
''|'#'*) continue ;;
esac
key="${line%%=*}"
value="${line#*=}"
case "$key" in
HOST|SHARE|MOUNT|CRED_FILE|VERS|FSTAB)
printf -v "$key" '%s' "$value"
;;
esac
done < "$CONFIG_FILE"
fi
if [[ -z "$HOST" || -z "$SHARE" || -z "$MOUNT" ]]; then
echo "找不到 $CONFIG_FILE,且未提供 HOST/SHARE/MOUNT 环境变量。" >&2
echo "示例: HOST=win-pc SHARE=ShareName MOUNT=/mnt/share sudo bash \"$0\"" >&2
exit 1
fi
if [[ ! "$HOST" =~ ^[A-Za-z0-9]([A-Za-z0-9._-]*[A-Za-z0-9])?$ ]]; then
echo "错误: 主机名/IP 含有异常字符: $HOST" >&2
exit 1
fi
case "$SHARE" in
*[[:space:]]*|*/*|*\\*|*'#'*)
echo "错误: 共享名不能包含空白、斜杠、反斜杠或 #: $SHARE" >&2
exit 1
;;
esac
if [[ "$MOUNT" != /* || "$MOUNT" =~ [[:space:]] ]]; then
echo "错误: 挂载点必须是不含空格的绝对路径: $MOUNT" >&2
exit 1
fi
mount_real="$(readlink -m "$MOUNT")"
if [[ "$mount_real" != "$MOUNT" ]]; then
echo "错误: 挂载点不能包含符号链接或 .. 路径: $MOUNT" >&2
exit 1
fi
case "$mount_real" in
/mnt/?*|/media/?*|/srv/?*|/home/?*) ;;
*)
echo "错误: 挂载点必须位于 /mnt、/media、/srv 或 /home 下: $MOUNT" >&2
exit 1
;;
esac
if [[ "$FSTAB" != "/etc/fstab" ]]; then
echo "错误: 只支持清理 /etc/fstab" >&2
exit 1
fi
sanitize() {
local s="$1"
s="${s//[^A-Za-z0-9._-]/_}"
printf '%s' "$s"
}
if [[ -z "$CRED_FILE" ]]; then
CRED_FILE="/etc/samba/credentials/winshare-$(sanitize "$HOST")-$(sanitize "$SHARE").cred"
fi
cred_real="$(readlink -m "$CRED_FILE")"
if [[ "$cred_real" != "$CRED_FILE" ]]; then
echo "错误: 凭据文件路径不能包含符号链接或 ..: $CRED_FILE" >&2
exit 1
fi
case "$cred_real" in
/etc/samba/credentials/winshare-*.cred) ;;
*)
echo "错误: 凭据文件必须位于 /etc/samba/credentials 且名为 winshare-*.cred: $CRED_FILE" >&2
exit 1
;;
esac
auto_unit="$(systemd-escape -p --suffix=automount "$MOUNT")"
mount_unit="$(systemd-escape -p --suffix=mount "$MOUNT")"
if mountpoint -q "$MOUNT"; then
mnt_type="$(findmnt -n -o FSTYPE -T "$MOUNT" 2>/dev/null || true)"
mnt_src="$(findmnt -n -o SOURCE -T "$MOUNT" 2>/dev/null || true)"
mnt_target="$(findmnt -n -o TARGET -T "$MOUNT" 2>/dev/null || true)"
if [[ "$mnt_target" == "$MOUNT" && "$mnt_type" == "autofs" ]]; then
: # systemd automount 的占位挂载,下面停止 automount 单元
elif [[ "$mnt_target" == "$MOUNT" && "$mnt_type" == "cifs" && "$mnt_src" == "//$HOST/$SHARE" ]]; then
: # 目标共享已经实际挂载
else
echo "错误: $MOUNT 当前挂载的是 $mnt_type $mnt_src,不是 //$HOST/$SHARE。" >&2
echo "为避免误卸载,已停止。" >&2
exit 1
fi
fi
systemctl stop "$auto_unit" 2>/dev/null || true
if mountpoint -q "$MOUNT"; then
mnt_type="$(findmnt -n -o FSTYPE -T "$MOUNT" 2>/dev/null || true)"
mnt_src="$(findmnt -n -o SOURCE -T "$MOUNT" 2>/dev/null || true)"
mnt_target="$(findmnt -n -o TARGET -T "$MOUNT" 2>/dev/null || true)"
if [[ "$mnt_target" == "$MOUNT" && "$mnt_type" == "autofs" ]]; then
echo "错误: 自动挂载单元仍占用 $MOUNT,已停止。" >&2
exit 1
fi
if [[ "$mnt_target" != "$MOUNT" || "$mnt_type" != "cifs" || "$mnt_src" != "//$HOST/$SHARE" ]]; then
echo "错误: $MOUNT 当前挂载的是 $mnt_type $mnt_src,不是 //$HOST/$SHARE。" >&2
echo "为避免误卸载,已停止。" >&2
exit 1
fi
systemctl stop "$mount_unit" 2>/dev/null || true
if mountpoint -q "$MOUNT"; then
if ! umount "$MOUNT"; then
echo "无法卸载 $MOUNT,可能仍有程序占用。请关闭相关程序后重试。" >&2
exit 1
fi
fi
else
systemctl stop "$mount_unit" 2>/dev/null || true
fi
if [[ -f "$FSTAB" ]]; then
cp -a "$FSTAB" "$FSTAB.bak.$(date +%Y%m%d-%H%M%S)"
python3 - "$FSTAB" "$MOUNT" "$HOST" "$SHARE" <<'PY'
import os
import pathlib
import stat
import sys
import tempfile
fstab, mount, host, share = sys.argv[1:5]
path = pathlib.Path(fstab)
text = path.read_text(encoding="utf-8", errors="surrogateescape")
unc = f"//{host}/{share}"
marker = f"# Windows share {unc} (added by setup-winshare.sh)"
kept = []
for line in text.splitlines(keepends=True):
if line.strip() == marker:
continue
fields = line.split("#", 1)[0].split()
if len(fields) >= 2 and fields[0] == unc and fields[1] == mount:
continue
kept.append(line)
new_text = "".join(kept)
if new_text == text:
sys.exit(0)
orig = path.stat()
fd, tmp = tempfile.mkstemp(prefix=".fstab-", dir=str(path.parent))
try:
with os.fdopen(
fd, "w", encoding="utf-8", errors="surrogateescape", newline=""
) as stream:
stream.write(new_text)
stream.flush()
os.fsync(stream.fileno())
os.chmod(tmp, stat.S_IMODE(orig.st_mode))
try:
os.chown(tmp, orig.st_uid, orig.st_gid)
except PermissionError:
pass
os.replace(tmp, path)
tmp = ""
finally:
if tmp and os.path.exists(tmp):
os.unlink(tmp)
PY
if awk -v u="//$HOST/$SHARE" -v m="$MOUNT" '
$1 == u && $2 == m { found = 1 }
END { exit !found }
' "$FSTAB"; then
echo "错误: $FSTAB 中仍有 //$HOST/$SHARE -> $MOUNT 的条目,已停止。" >&2
exit 1
fi
fi
rm -f "$CRED_FILE"
if [[ -f "$CONFIG_FILE" ]]; then
rm -f "$CONFIG_FILE"
fi
systemctl daemon-reload
systemctl reset-failed "$mount_unit" 2>/dev/null || true
rmdir "$MOUNT" 2>/dev/null || true
echo "已移除 //$HOST/$SHARE 的自动挂载配置、凭据文件和 fstab 条目。"
+382
View File
@@ -0,0 +1,382 @@
#!/usr/bin/env bash
# 配置 Windows SMB 共享的按需自动挂载(cifs + systemd automount)
# 交互输入 Windows 主机、共享名和挂载点;也可用环境变量预填。
set -euo pipefail
here="$(cd "$(dirname "$(readlink -f "$0")")" && pwd)"
HOST="${HOST:-}"
SHARE="${SHARE:-}"
MOUNT="${MOUNT:-}"
VERS="${VERS:-3.0}"
FSTAB="${FSTAB:-/etc/fstab}"
CRED_DIR="${CRED_DIR:-/etc/samba/credentials}"
CONFIG_FILE="${CONFIG_FILE:-/etc/winshare.conf}"
DRY_RUN="${DRY_RUN:-0}"
if [[ "$DRY_RUN" != "1" && ${EUID:-$(id -u)} -ne 0 ]]; then
echo "请使用 sudo 运行: sudo bash \"$0\"" >&2
exit 1
fi
OWNER_UID="${OWNER_UID:-${SUDO_UID:-}}"
OWNER_GID="${OWNER_GID:-${SUDO_GID:-}}"
if [[ "$DRY_RUN" != "1" ]]; then
for cmd in install readlink systemctl systemd-escape mountpoint findmnt getent awk cp tr dirname basename find; do
if ! command -v "$cmd" >/dev/null 2>&1; then
echo "错误: 缺少依赖 $cmd" >&2
exit 1
fi
done
fi
if [[ -z "$OWNER_UID" || -z "$OWNER_GID" ]]; then
echo "提示: 未通过 sudo 运行,无法自动判断挂载归属用户(可用 id -u / id -g 查看)。"
fi
if [[ -z "$OWNER_UID" ]]; then
IFS= read -r -p "挂载归属的 Linux 用户 UID [1000]: " OWNER_UID
OWNER_UID="${OWNER_UID:-1000}"
fi
if [[ -z "$OWNER_GID" ]]; then
IFS= read -r -p "挂载归属的 Linux 组 GID [1000]: " OWNER_GID
OWNER_GID="${OWNER_GID:-1000}"
fi
if [[ ! "$OWNER_UID" =~ ^[0-9]+$ || ! "$OWNER_GID" =~ ^[0-9]+$ ]]; then
echo "错误: UID/GID 必须是数字: uid=$OWNER_UID gid=$OWNER_GID" >&2
exit 1
fi
sanitize() {
local s="$1"
s="${s//[^A-Za-z0-9._-]/_}"
printf '%s' "$s"
}
if [[ -z "$HOST" ]]; then
IFS= read -r -p "Windows 主机名或 IP: " HOST
HOST="${HOST%$'\r'}"
fi
if [[ -z "$SHARE" ]]; then
IFS= read -r -p "共享名(Windows 上 net share 可查看): " SHARE
SHARE="${SHARE%$'\r'}"
fi
if [[ -z "$MOUNT" ]]; then
default_share="$(printf '%s' "$SHARE" | tr '[:upper:]' '[:lower:]' | tr -c 'a-z0-9._-' '_')"
IFS= read -r -p "Linux 挂载点 [/mnt/windows-$default_share]: " MOUNT
MOUNT="${MOUNT:-/mnt/windows-$default_share}"
fi
if [[ -z "$HOST" || -z "$SHARE" ]]; then
echo "HOST 和 SHARE 不能为空" >&2
exit 1
fi
if [[ ! "$HOST" =~ ^[A-Za-z0-9]([A-Za-z0-9._-]*[A-Za-z0-9])?$ ]]; then
echo "主机名/IP 含有异常字符: $HOST" >&2
exit 1
fi
case "$SHARE" in
*[[:space:]]*|*/*|*\\*|*'#'*)
echo "共享名不能包含空白、斜杠、反斜杠或 #: $SHARE" >&2
exit 1
;;
esac
if [[ "$MOUNT" != /* || "$MOUNT" =~ [[:space:]] ]]; then
echo "挂载点必须是不含空格的绝对路径: $MOUNT" >&2
exit 1
fi
if [[ "$DRY_RUN" != "1" ]]; then
mount_real="$(readlink -m "$MOUNT")"
if [[ "$mount_real" != "$MOUNT" ]]; then
echo "错误: 挂载点不能包含符号链接或 .. 路径: $MOUNT" >&2
exit 1
fi
case "$mount_real" in
/mnt/?*|/media/?*|/srv/?*|/home/?*) ;;
*)
echo "错误: 挂载点必须位于 /mnt、/media、/srv 或 /home 下: $MOUNT" >&2
exit 1
;;
esac
if [[ "$FSTAB" != "/etc/fstab" ]]; then
echo "错误: 实际运行时只允许写入 /etc/fstab(测试请设置 DRY_RUN=1)" >&2
exit 1
fi
if [[ "$(dirname "$CONFIG_FILE")" != "/etc" || "$(basename "$CONFIG_FILE")" != winshare*.conf ]]; then
echo "错误: 配置文件必须位于 /etc 且命名为 winshare*.conf: $CONFIG_FILE" >&2
exit 1
fi
if [[ "$CRED_DIR" != "/etc/samba/credentials" ]]; then
echo "错误: 实际运行时凭据目录必须是 /etc/samba/credentials" >&2
exit 1
fi
fi
if [[ -f "$CONFIG_FILE" ]]; then
old_host=""
old_share=""
old_mount=""
while IFS= read -r line || [[ -n "$line" ]]; do
case "$line" in
HOST=*) old_host="${line#HOST=}" ;;
SHARE=*) old_share="${line#SHARE=}" ;;
MOUNT=*) old_mount="${line#MOUNT=}" ;;
esac
done < "$CONFIG_FILE"
if [[ -n "$old_host" ]]; then
if [[ "$old_host" != "$HOST" || "$old_share" != "$SHARE" || "$old_mount" != "$MOUNT" ]]; then
echo "错误: $CONFIG_FILE 已对应 //$old_host/$old_share -> $old_mount。" >&2
echo "请使用不同的 CONFIG_FILE(例如 CONFIG_FILE=/etc/winshare-2.conf)或先卸载原配置。" >&2
exit 1
fi
fi
fi
echo "目标共享: //$HOST/$SHARE"
echo "挂载点 : $MOUNT"
echo
if [[ "$DRY_RUN" != "1" ]] \
&& [[ ! "$HOST" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]] \
&& ! getent hosts "$HOST" >/dev/null 2>&1; then
echo "警告: 无法解析主机名 $HOST。"
echo " 可以改用 IP 重新运行: HOST=<IP> sudo bash \"$0\""
read -r -p "仍然继续? [y/N] " answer
[[ "$answer" =~ ^[Yy]$ ]] || exit 1
fi
# 安装 cifs-utils(提供 mount.cifs)
if [[ "$DRY_RUN" != "1" ]] && ! command -v mount.cifs >/dev/null 2>&1; then
if ! command -v apt-get >/dev/null 2>&1; then
echo "错误: 未找到 mount.cifs,且系统没有 apt-get。" >&2
echo "请先使用发行版的包管理器安装 cifs-utils。" >&2
exit 1
fi
echo "安装 cifs-utils ..."
if ! DEBIAN_FRONTEND=noninteractive apt-get install -y cifs-utils; then
echo "首次安装失败,尝试 apt-get update 后重试 ..."
apt-get update
DEBIAN_FRONTEND=noninteractive apt-get install -y cifs-utils
fi
fi
if [[ "$DRY_RUN" != "1" ]] && ! command -v mount.cifs >/dev/null 2>&1; then
echo "错误: cifs-utils 安装后仍找不到 mount.cifs" >&2
exit 1
fi
# 检查 fstab 是否已有同一挂载点(在输入密码前检查)
if [[ "$DRY_RUN" != "1" ]] && awk -v m="$MOUNT" '
/^[[:space:]]*#/ { next }
$2 == m { found = 1 }
END { exit !found }
' "$FSTAB"; then
echo "错误: $FSTAB 中已经存在挂载点 $MOUNT 的条目,请先手动处理。" >&2
exit 1
fi
if [[ "$DRY_RUN" != "1" ]]; then
if [[ -e "$MOUNT" && ! -d "$MOUNT" ]]; then
echo "错误: $MOUNT 已存在且不是目录" >&2
exit 1
fi
if [[ -d "$MOUNT" ]] && mountpoint -q "$MOUNT"; then
mnt_type="$(findmnt -n -o FSTYPE -T "$MOUNT" 2>/dev/null || true)"
mnt_src="$(findmnt -n -o SOURCE -T "$MOUNT" 2>/dev/null || true)"
mnt_target="$(findmnt -n -o TARGET -T "$MOUNT" 2>/dev/null || true)"
if [[ "$mnt_target" == "$MOUNT" && "$mnt_type" == "autofs" ]]; then
echo "错误: $MOUNT 当前被 automount 占用;请先停止自动挂载,或先运行 remove-winshare.sh。" >&2
exit 1
elif [[ "$mnt_target" == "$MOUNT" && "$mnt_type" == "cifs" && "$mnt_src" == "//$HOST/$SHARE" ]]; then
echo "$MOUNT 已挂载目标共享,先卸载 ..."
if ! umount "$MOUNT"; then
echo "错误: 无法卸载 $MOUNT" >&2
exit 1
fi
else
echo "错误: $MOUNT 当前挂载的是 $mnt_type $mnt_src,而不是 //$HOST/$SHARE。" >&2
echo "为避免误卸载/覆盖,已停止。" >&2
exit 1
fi
fi
if [[ -d "$MOUNT" ]]; then
if [[ -n "$(find "$MOUNT" -mindepth 1 -maxdepth 1 -print -quit 2>/dev/null)" ]]; then
echo "错误: $MOUNT 不是空目录。请选择新的目录或空目录。" >&2
exit 1
fi
fi
fi
echo "Windows 账号格式:"
echo " 本地账号 alice 或 $HOST\\alice"
echo " 微软账号 MicrosoftAccount\\邮箱@example.com"
echo " 域账号 DOMAIN\\用户名"
echo
IFS= read -r -p "Windows 用户名: " WINUSER
WINUSER="${WINUSER%$'\r'}"
if [[ -z "$WINUSER" ]]; then
echo "用户名不能为空" >&2
exit 1
fi
# 本地账号通常使用 Windows 计算机名作为“域”,默认取 HOST;
# 如果 HOST 是 IP,则默认不指定域;输入 - 也表示不指定
default_domain="$HOST"
if [[ "$HOST" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
default_domain=""
fi
WINDOMAIN="${DOMAIN:-$default_domain}"
if [[ "$WINUSER" == *\\* ]]; then
WINDOMAIN="${WINUSER%%\\*}"
WINUSER="${WINUSER#*\\}"
fi
domain_hint="${WINDOMAIN:-不指定}"
IFS= read -r -p "域/工作组 [$domain_hint](输入 - 表示不指定): " INPUT_DOMAIN
INPUT_DOMAIN="${INPUT_DOMAIN%$'\r'}"
if [[ -n "$INPUT_DOMAIN" ]]; then
if [[ "$INPUT_DOMAIN" == "-" ]]; then
WINDOMAIN=""
else
WINDOMAIN="$INPUT_DOMAIN"
fi
fi
while true; do
IFS= read -r -s -p "Windows 密码: " WINPASS
echo
IFS= read -r -s -p "再输入一次: " WINPASS2
echo
if [[ "$WINPASS" == "$WINPASS2" ]]; then
break
fi
echo "两次输入不一致,请重试。"
done
CRED_FILE="$CRED_DIR/winshare-$(sanitize "$HOST")-$(sanitize "$SHARE").cred"
MNT_OPTS="credentials=$CRED_FILE,uid=$OWNER_UID,gid=$OWNER_GID,file_mode=0660,dir_mode=0770,nounix,forceuid,forcegid,iocharset=utf8,vers=$VERS"
FSTAB_OPTS="$MNT_OPTS,nofail,_netdev,nosuid,nodev,x-systemd.automount,x-systemd.idle-timeout=10min"
write_credentials() {
{
printf 'username=%s\n' "$WINUSER"
printf 'password=%s\n' "$WINPASS"
if [[ -n "$WINDOMAIN" ]]; then
printf 'domain=%s\n' "$WINDOMAIN"
fi
} > "$CRED_FILE"
}
if [[ "$DRY_RUN" == "1" ]]; then
echo
echo "=== DRY RUN ==="
echo "凭据文件: $CRED_FILE"
echo "挂载选项: $MNT_OPTS"
echo "fstab 行 : //$HOST/$SHARE $MOUNT cifs $FSTAB_OPTS 0 0"
mkdir -p "$CRED_DIR" "$MOUNT" "$(dirname "$FSTAB")" "$(dirname "$CONFIG_FILE")"
(
umask 077
write_credentials
)
printf '//%s/%s %s cifs %s 0 0\n' "$HOST" "$SHARE" "$MOUNT" "$FSTAB_OPTS" >> "$FSTAB"
printf 'HOST=%s\nSHARE=%s\nMOUNT=%s\nCRED_FILE=%s\nVERS=%s\nFSTAB=%s\n' \
"$HOST" "$SHARE" "$MOUNT" "$CRED_FILE" "$VERS" "$FSTAB" > "$CONFIG_FILE"
exit 0
fi
install -d -m 0700 "$CRED_DIR"
(
umask 077
write_credentials
)
chmod 600 "$CRED_FILE"
chown root:root "$CRED_FILE"
unset WINPASS WINPASS2
if [[ ! -d "$MOUNT" ]]; then
mkdir -p "$MOUNT"
fi
if mountpoint -q "$MOUNT"; then
echo "错误: $MOUNT 在配置期间被其他挂载占用,已停止。" >&2
exit 1
fi
echo "测试挂载 ..."
if ! mount -t cifs "//$HOST/$SHARE" "$MOUNT" -o "$MNT_OPTS"; then
echo
echo "挂载失败。请检查:" >&2
echo " 1. Windows 上共享名是否为 '$SHARE'(在 Windows 运行 net share 查看)" >&2
echo " 2. 用户名/密码/域是否正确(本地账号可试 $HOST\\用户名 或 WORKGROUP)" >&2
echo " 3. Windows 网络配置文件是否为“专用”,并启用“文件和打印机共享”" >&2
echo " 4. 若错误为 mount error(2),通常是共享名不对;mount error(13) 多为凭据/权限问题" >&2
echo " 5. 可尝试其他 SMB 版本: VERS=2.1 或 VERS=3.1.1 sudo bash \"$0\"" >&2
exit 1
fi
echo "测试挂载成功,目录内容:"
ls -la "$MOUNT" | head -20 || true
test_src="$(findmnt -n -o SOURCE -T "$MOUNT" 2>/dev/null || true)"
if [[ "$test_src" == "//$HOST/$SHARE" ]]; then
umount "$MOUNT"
else
echo "警告: 测试挂载的来源为 '$test_src',未自动卸载,请手动检查 $MOUNT。" >&2
exit 1
fi
backup="$FSTAB.bak.$(date +%Y%m%d-%H%M%S)"
cp -a "$FSTAB" "$backup"
if [[ -s "$FSTAB" && "$(tail -c 1 "$FSTAB")" != $'\n' ]]; then
printf '\n' >> "$FSTAB"
fi
{
printf '# Windows share //%s/%s (added by setup-winshare.sh)\n' "$HOST" "$SHARE"
printf '//%s/%s %s cifs %s 0 0\n' "$HOST" "$SHARE" "$MOUNT" "$FSTAB_OPTS"
} >> "$FSTAB"
{
printf 'HOST=%s\n' "$HOST"
printf 'SHARE=%s\n' "$SHARE"
printf 'MOUNT=%s\n' "$MOUNT"
printf 'CRED_FILE=%s\n' "$CRED_FILE"
printf 'VERS=%s\n' "$VERS"
printf 'FSTAB=%s\n' "$FSTAB"
} > "$CONFIG_FILE"
chmod 600 "$CONFIG_FILE"
if ! findmnt --verify >/dev/null 2>&1; then
echo "警告: /etc/fstab 校验有告警,请运行 findmnt --verify 检查。" >&2
fi
systemctl daemon-reload
auto_unit="$(systemd-escape -p --suffix=automount "$MOUNT")"
mount_unit="$(systemd-escape -p --suffix=mount "$MOUNT")"
if ! systemctl start "$auto_unit"; then
echo "启动自动挂载单元 $auto_unit 失败。" >&2
systemctl status "$auto_unit" --no-pager || true
exit 1
fi
echo "触发自动挂载 ..."
ls -la "$MOUNT" >/dev/null 2>&1 || true
if ! mountpoint -q "$MOUNT"; then
echo "自动挂载失败。" >&2
journalctl -u "$mount_unit" -n 30 --no-pager || true
exit 1
fi
echo
echo "挂载成功:"
findmnt "$MOUNT" || true
echo
if [[ -n "${SUDO_USER:-}" ]] && command -v runuser >/dev/null 2>&1; then
if runuser -u "$SUDO_USER" -- test -r "$MOUNT"; then
echo "用户 $SUDO_USER 可以访问 $MOUNT"
else
echo "警告: 用户 $SUDO_USER 无法读取 $MOUNT,请检查 uid/gid 和 Windows 共享权限。" >&2
fi
fi
echo "fstab 备份: $backup"
echo "以后访问 $MOUNT 时会自动挂载,空闲 10 分钟自动卸载。"
echo "卸载: sudo umount $MOUNT"
echo "移除配置: sudo bash \"$here/remove-winshare.sh\""