在Ubuntu下用autofs自动挂载NAS Samba分区

Contents

之前在 在macOS下自动挂载NAS Samba分区和Ubuntu远程分区 用macOS的automount实现了Samba和NFS分区的按需挂载。在Ubuntu也能实现类似功能:访问NAS Samba分区时,自动挂载这些分区。

安装autofs #

使用autofs可以实现最接近macOS automount的功能:

💡 Package: autofs

Maintainer: Ubuntu Developers [email protected]

Original-Maintainer: Mike Gabriel [email protected]

Bugs: https://bugs.launchpad.net/ubuntu/+filebug

Homepage: https://www.kernel.org/pub/linux/daemons/autofs/v5/

Description: kernel-based automounter for Linux Autofs controls the operation of the automount daemons. The automount daemons automatically mount filesystems when they are used and unmount them after a period of inactivity. This is done based on a set of pre-configured maps.

.

The kernel automounter implements an almost complete SunOS style automounter under Linux. A recent version of the kernel autofs4 module (builtin or separate) is required.

.

This is the autofs daemon.

在Ubuntu下安装autofs和Samba工具包:

shell
sudo apt install -y autofs cifs-utils

direct map自动挂载 #

创建主配置文件,我通过direct map自动挂载,10分钟无访问后自动卸载:

shell
cat << EOF | sudo tee /etc/auto.master
/-      /etc/auto.smb      --timeout=600
EOF

# 确保文件权限
sudo chmod 644 /etc/auto.master

创建Samba挂载点,Ubuntu不会像macOS那样创建恼人的._*文件,可以默认rw模式。替换下面的usernamenas-ip-address和挂载目录:

shell
cat << EOF | sudo tee /etc/auto.smb
/mnt/OpenData -fstype=cifs,rw,credentials=/home/username/.smbcredentials,vers=3.0,uid=1000,gid=1000 ://nas-ip-address/OpenData
/mnt/Software -fstype=cifs,rw,credentials=/home/username/.smbcredentials,vers=3.0,uid=1000,gid=1000 ://nas-ip-address/Software
/mnt/Downloads -fstype=cifs,rw,credentials=/home/username/.smbcredentials,vers=3.0,uid=1000,gid=1000 ://nas-ip-address/Downloads
/mnt/Videos -fstype=cifs,rw,credentials=/home/username/.smbcredentials,vers=3.0,uid=1000,gid=1000 ://nas-ip-address/Videos
EOF

# 确保文件权限
sudo chmod 644 /etc/auto.smb

创建凭据文件,并设置权限,替换下面的nas_userpassword

shell
cat > ~/.smbcredentials << EOF
username=nas_user
password=password
EOF

chmod 600 ~/.smbcredentials

自动启动autofs,下次访问时自动挂载:

shell
sudo systemctl restart autofs
sudo systemctl enable autofs

ls /mnt/OpenData

闲置10分钟后会自动卸载。