Automounting remote filesystems with AutoFS and SSHFS


Installation

We need to install a few things first to be able to make this work:
sudo apt-get install autofs sshfs


Manual mounting

Then we'll make a folder to mount our folders in, for example /mnt/sshfs:
sudo mkdir /mnt/sshfs

To mount our remote filesystem for testing purposes we can do:

sudo sshfs -o allow_other,default_permissions [email protected]:/Directory /mnt/sshfs  


Type in the password for the remote user when prompted

Assuming everything went okay we should now be able to access the remote filesystem just like we would be able to access a local folder:
ls /mnt/sshfs
That should list most of the contents of the remote folder directly in the local terminal

To unmount the folder run:
sudo fusermount -u /mnt/sshfs


Pre-configuration for AutoFS

To be able to mount the remote filesystem without interference and by the use of AutoFS we need to setup passwordless SSH login for both the normal user and root, so follow that guide and get back here after.

We should now be able to login to the remote server with SSH without getting a password prompt, both with the normal user and with the root user.
ssh [email protected]
If that works, we can try passwordless mounting as well.

sudo sshfs -o allow_other,default_permissions [email protected]:/Directory /mnt/sshfs  


To unmount it again, just run the same command as earlier:
sudo fusermount -u /mnt/sshfs


AutoFS-configuration

There are multiple configuration files to edit for AutoFS, but we'll only concentrate on two in this guide, /etc/auto.master and another one we'll make ourselves called /etc/auto.sshfs
With /etc/auto.master we'll open it up for editing with this command:
sudo nano /etc/auto.master
then we will add this line:

/mnt /etc/auto.sshfs uid=1000,gid=1000,--timeout=30,--ghost
  • uid and gid are the local user and group id you want the mount to belong to.
  • --ghost means the directory will be "ghost mounted" so you see it with an ls but the actual mount is actually done when you access it
  • --timeout sets the maximum inactivity time for the mount. After that it gets automatically unmounted again.

/etc/auto.sshfs we will open up for editing in the same way: sudo nano /etc/auto.sshfs
Since this is a new file it will be empty, and we'll add this line to it:

sshfs -fstype=fuse,rw,nodev,nonempty,noatime,allow_other,max_read=65536 \:sshfs\#[email protected]\:/Directory  

Restarting AutoFS

Before we can see that it works we need to restart the AutoFS-service so that it loads the new configuration that we've created:
sudo service autofs restart


Final testing

Now we can do a final test to see if it works by running:
ls /mnt/sshfs
If it lists most of the contents of the remote folder directly in the local terminal like before, the setup is working as it should.