Seamlessly mount NAS with autofs
In an earlier post I talked about how my selfmade NAS goes to sleep when not in use. However, manually waking the NAS up and mounting it again is quite cumbersome.
Luckily, there is an easy solution. autofs allows you to mount on demand. That alone is already great for network shares, but the best part is: the configuration can be a script.
In this post we’re going to explore how to mount network shares on demand with automatic “Wake On Lan”.
Setting everything up
I’m using my Pop!_OS machine for this setup, but any Linux distribution should work (there are probably equivalents for macOS and Windows too).
First up: installing our dependencies.
sudo apt install autofs wakeonlan
With that out of the way we can begin setting up autofs.
I’m going to use the path /media/NAS for my network share. The main configuration is in /etc/auto.master. By adding the following line to that file we tell it that every time a directory is accessed in /media the script called /usr/local/bin/autofs-nas should be run (it will pass the directory name as the first parameter).
echo "/media program:/usr/local/bin/autofs-nas --ghost browse" >> /etc/auto.master
Next, we’re going to create /usr/local/bin/autofs-nas.
#!/bin/bash
folder="NAS"
nas="<name of your nas in /etc/hosts>"
mac="<mac address of your nas>"
path="<path of your share as shown in showmount>"
mountopts="-fstype=nfs4,rw,relatime"
test "$1" == $folder || exit 0
if ! ping $nas -c 1 -l 1 -qn > /dev/null 2>&1; then
wakeonlan mac > /dev/null
for n in `seq 1 120`; do
ping $nas -c 1 -l 1 -qn > /dev/null 2>&1 && break
sleep 1
done
fi
echo "$mountopts $nas:$path"
We first check if the accessed directory is the directory we want to mount our share in. If not, we exit.
Then we ping the NAS to check if it’s already awake. If not, we send the WOL magic packet and ping the NAS once every second until it is awake (for up to 120 seconds).
Finally, we echo the options for autofs.
Using it
And now it’s time to experience the magic. Whenever you try to access /media/NAS the script we just wrote will be run.
If the NAS was asleep, that first access will take a couple of seconds, but after that everything should work smoothly (until you went to get lunch and the NAS went back to sleep).