访问指定路径时如何自动运行预设脚本完成自动挂载等操作?
这个需求可以实现,优先推荐使用系统原生的systemd automount机制,也可根据场景选择inotify监听方案,具体实现如下:
方案1:systemd automount(生产环境首选,稳定无遗漏)
systemd 原生支持路径按需访问触发挂载逻辑,无需hook系统调用,不会漏过任何访问请求,配置步骤如下:
- 把你的挂载逻辑整理为独立可执行脚本,例如存为
/usr/local/bin/mount_custom_path.sh,示例内容:
#!/bin/bash echo "scripting!" mkdir -p /non_existing_path # 此处替换为你实际的挂载命令/业务逻辑
给脚本添加执行权限:
chmod +x /usr/local/bin/mount_custom_path.sh
- 编写systemd挂载单元,存到
/etc/systemd/system/non_existing_path.mount,文件命名必须和目标路径的斜杠替换为横杠的格式一致,示例目标路径为/non_existing_path,内容如下:
[Unit] Description=Custom path mount service [Mount] What=dummy Where=/non_existing_path Type=none ExecMount=/usr/local/bin/mount_custom_path.sh TimeoutSec=30
- 编写systemd automount触发单元,存到
/etc/systemd/system/non_existing_path.automount,内容如下:
[Unit] Description=Automount trigger for custom path [Automount] Where=/non_existing_path # 空闲1小时后自动卸载,不需要自动卸载可删除该行 TimeoutIdleSec=3600 [Install] WantedBy=multi-user.target
- 加载配置并启用服务:
systemctl daemon-reload systemctl enable --now non_existing_path.automount
配置完成后,任何对/non_existing_path的访问操作(包括cd、touch、程序读写文件等)都会优先触发你写的脚本执行,脚本执行完成后才会放行后续访问请求。
方案2:inotify监听(适合临时测试场景)
如果不想使用systemd,也可以用inotifywait监听路径访问事件触发脚本,该方案需要后台常驻进程,存在小概率漏事件的可能,仅适合测试使用:
- 安装inotify工具包:
# Debian/Ubuntu apt install inotify-tools # CentOS/RHEL yum install inotify-tools
- 编写监听脚本
/usr/local/bin/watch_path.sh,内容如下:
#!/bin/bash TARGET="/non_existing_path" PARENT_DIR=$(dirname "$TARGET") inotifywait -m -e access,open,create "$PARENT_DIR" | while read path action file; do full_path="${path%/}/${file}" if [[ "$full_path" == "$TARGET"* ]] && [ ! -e "$TARGET" ]; then /usr/local/bin/mount_custom_path.sh fi done
- 给脚本加执行权限后,配置为开机自启的后台服务即可。
内容的提问来源于stack exchange,提问作者Gulzar
相关产品推荐
相关产品推荐

