centos 7 实现自动按需挂载

此前我们比如要挂载 nfs,都是将其写到/etc/fstab

[root@node-server-1 nfs]# cat /etc/fstab

#
# /etc/fstab
# Created by anaconda on Tue May  2 07:21:59 2017
#
# Accessible filesystems, by reference, are maintained under '/dev/disk'
# See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info
#
/dev/mapper/cl-root     /                       xfs     defaults        0 0
UUID=fc90e3db-ce52-43d0-ac08-6b8ca4dc25ab /boot                   xfs     defaults        0 0
/dev/mapper/cl-swap     swap                    swap    defaults        0 0
192.168.50.156:/opt /mnt nfs defaults 0 0

但是,我们并不是每时每刻都在使用这个共享目录,我们可以通过 autofs 实现自动按需挂载,怎么实现呢? 我们来看下。

安装

yum -y install autofs

配置文件

autofs的主要配置文件有两个,分别是/etc下的auto.master和auto.misc。其中,auto.master是起控制作用的,它定义了挂在点和automount动作的文件。其内容如下:

[root@node-server-1 etc]# ll auto*
-rw-r--r--. 1 root root 13386 Nov  5 14:19 autofs.conf
-rw-------. 1 root root   232 Nov  5 14:19 autofs_ldap_auth.conf
-rw-r--r--. 1 root root   795 Nov  5 14:19 auto.master
-rw-r--r--. 1 root root   524 Nov  5 14:19 auto.misc
-rwxr-xr-x. 1 root root  1260 Nov  5 14:19 auto.net
-rwxr-xr-x. 1 root root   687 Nov  5 14:19 auto.smb

auto.master.d:
total 0
[root@node-server-1 etc]#

auto.master 配置

[root@node-server-1 ~]# vim /etc/auto.master
/misc    /etc/auto.misc
/nfs    /etc/auto.nfs # 自定义一条 表示挂载在 nfs 目录下,这个目录不需要你创建,程序会自动创建。
……

auto.nfs 配置

1.拷贝 auto.misc文件到 auto.nfs

mv /etc/auto.misc /etc/auto.nfs

2.编辑 auto.nfs,内容如下

[root@node-server-1 nfs]# cat /etc/auto.nfs
#
# This is an automounter map and it has the following format
# key [ -mount-options-separated-by-comma ] location
# Details may be found in the autofs(5) manpage

#cd        -fstype=iso9660,ro,nosuid,nodev    :/dev/cdrom
nfs        -fstype=nfs    192.168.50.156:/opt #添加这一条,表示挂载到 nfs 目录,文件类型是 nfs  后面是 nfs 的地址
……

3.挂载完之后,重启服务

systemctl restart autofs.service

4.然后查看,发现 nfs 目录下什么都没有

[root@node-server-1 nfs]# cd /nfs/
[root@node-server-1 nfs]# ls

5.然后,我们 cd nfs 看下,发现就有了,至此,实现了 nfs 的自动挂载。

[root@node-server-1 nfs]# cd nfs
[root@node-server-1 nfs]# ls
2017-04-10-raspbian-jessie-lite.img
2017-04-10-raspbian-jessie-lite.zip
CentOS-6.8-x86_64-bin-DVD1.iso
CentOS-7-x86_64-DVD-1611.iso
cn_windows_7_ultimate_with_sp1_x86_dvd_u_677486.iso
linux-4.10.14
linux-4.10.14.tar.xz
natap.log
rh
ubuntu-16.04.2-server-amd64.iso
ubuntu-16.04-preinstalled-server-armhf+raspi3.img
win1064.iso
WOL

6.设置超时时间,当超时后自动断开

[root@node-server-1 yum.repos.d]# cat /etc/sysconfig/autofs
#
# Init syatem options
#
# If the kernel supports using the autofs miscellanous device
# and you wish to use it you must set this configuration option
# to "yes" otherwise it will not be used.
#
USE_MISC_DEVICE="yes"
#
# Use OPTIONS to add automount(8) command line options that
# will be used when the daemon is started.
#
#OPTIONS=""
TIMEOUT=300
#

参考资料http://www.turbolinux.com.cn/turbo/wiki/doku.php?id=%E7%B3%BB%E7%BB%9F%E7%AE%A1%E7%90%86:autofs