Automatically mount samba shares using autofs

I created a mount in /etc/fstab for a samba share. This is a standard fstab entry to mount a samba share using cifs:

/myserver/myshare /media/myshare cifs username=myuser,password=mypass,uid=myuser,gid=myuser,iocharset=utf8 0 0

The problem with this is that if you are on a laptop and use a wireless connection, when you boot your system the wireless network will not be up before it tries to mount the share. When you shut the system down the wireless network will be down before the system has a chance to unmount the share, causing a hang.

The solution for this is to use autofs which enables the samba share to be mounted on-demand when the user accesses it. Quite simply, this is almost magical.

These instructions are for Debian but are probably applicable for Ubuntu and any Debian derivatives like Linux Mint.

1. Install autofs and smbclient (and cifs if it isn’t already installed).
apt install autofs smbclient cifs-utils

2. Create an autofs mount point. I chose to create mine under /media:
mkdir /media/auto
This needs to be it’s own directory, in other words don’t plan to mount anything else in /media/auto except what autofs puts there.

3. Create the credentials directory and the credentials file for your samba server. If the server name is foobar then the credentials file needs to be named foobar. If you’re curious how autofs will automagically find this file based on the server name look at the script in /etc/auto.smb
mkdir /etc/creds
touch /etc/creds/myserver

4. Edit /etc/creds/myserver and add the following contents:
username=myusername
password=mypassword

5. Restrict access to the credentials file:
chmod 600 /etc/creds/myserver

6. Add the following line for the mount point to /etc/auto.master:
/media/auto /etc/auto.smb –timeout=300

7. Restart the autofs daemon:
sudo service restart autofs

8. Now check and verify that you can access the autofs share:
ls /media/auto/myserver
You should see /media/auto/myserver/myshare appear.
ls /media/auto/myserver/myshare
You should see the directory listing of myshare

9. If necessary you can check the syslog for output from autofs:
tail -f /var/log/syslog