3.6.5 自动挂载autofs原理与配置

autofs 是按需自动挂载机制:访问触发挂载,空闲超时自动卸载,避免长期挂载阻塞与资源占用。核心由 autofs 守护进程 + 内核 automount 模块协作。

原理草图:

文章图片

安装与服务管理:

# 安装
sudo yum install -y autofs   # RHEL/CentOS
# 或
sudo apt-get install -y autofs   # Debian/Ubuntu

# 启动与开机自启
sudo systemctl enable --now autofs
sudo systemctl status autofs

命令解释:
- enable --now:立刻启动并设置开机自启
- status:查看运行状态与错误信息

基础配置示例(间接映射 NFS):

# /etc/auto.master
/mnt/auto /etc/auto.misc --timeout=300 --ghost

# /etc/auto.misc
data -rw,soft,intr 192.168.1.10:/export/data
logs -rw,hard,timeo=30,retrans=3 192.168.1.10:/export/logs

说明:
- --timeout=300:空闲 300 秒卸载
- --ghost:即使未挂载也显示目录项
- -rw,soft,intr:软挂载、可中断;适合不允许长时间阻塞
- -hard,timeo,retrans:硬挂载超时与重试次数,适合强一致场景

验证与使用:

# 重新加载配置
sudo systemctl reload autofs

# 触发挂载
ls /mnt/auto/data
df -h | grep /mnt/auto

# 查看映射
automount -m
cat /proc/mounts | grep /mnt/auto

直接映射示例(固定路径挂载):

# /etc/auto.master
/- /etc/auto.direct --timeout=120

# /etc/auto.direct
/opt/shared -fstype=nfs4,rw 192.168.1.10:/export/shared

注意:直接映射会占用固定路径,避免与本地目录冲突。

CIFS 示例(访问 Windows 共享):

# /etc/auto.misc
share -fstype=cifs,username=ops,password='P@ssw0rd',uid=1000,gid=1000 //192.168.1.20/share

常见故障排查:

# 1) 服务状态与日志
systemctl status autofs
journalctl -u autofs -xe

# 2) 语法检查(观察解析后的映射)
automount -m

# 3) 网络与权限
ping 192.168.1.10
showmount -e 192.168.1.10   # NFS 服务器导出列表

# 4) 挂载失败时手工测试
sudo mount -t nfs 192.168.1.10:/export/data /mnt/test

排查要点:
- 映射文件语法是否正确(空格、字段顺序)
- 网络是否可达、NFS/CIFS 权限是否允许
- SELinux 是否拦截(必要时 getenforce/setenforce 0 临时验证)

练习:
1) 配置 /mnt/auto 自动挂载两条 NFS 目录,设置超时 120 秒,访问后验证自动卸载。
2) 将一个 CIFS 共享加入 autofs,要求所有者 uid/gid 为 1000,验证写入。
3) 手工制造网络不可达,观察 softhard 挂载行为差异并记录响应时间。