Automounting a remote server over SSH with sshfs and autofs
Sometimes it can be pretty useful to access a remote system's filesystem from your own, and sometimes NFS isn't a great fit for the connectivity at hand.
It is, however, possible to use sshfs
to mount a remote filesystem on pretty much any box that you can SSH to - giving quite a bit of convenience without the need to make changes at the remote end.
This documentation details how to create an auto-mounting SSHFS mount
The first thing we need to know, is the path (on the remote end) that we intend to mount. Finding that may be as simple as SSHing over and running
pwd
On your client system, you need to install both sshfs
and autofs
sudo apt-get install autofs sshfs
Then create a directory for your mounts to live in
mkdir ~/mounts
We'll want the mounts to use our UID and GID, so check what they are
UID=`id -u`
GID=`id -g`
Then, we want to append a line to the autofs
config
echo "/home/$USER/mounts /etc/autofs.sshfs uid=$UID,gid=$GID,--timeout=60,--ghost" | sudo tee -a /etc/auto.master
(--timeout
specifies how long a mount can be idle before it's unmounted, adjust as needed. --ghost
simple tells autofs
to create the mount directories even if the filesystem isn't currently mounted)
Next, we need to create the mapping file
echo "mac -fstype=fuse,rw,allow_other :sshfs\#btasker@mac.home\:/Users/btasker" | sudo tee /etc/autofs.sshfs
This tells autofs:
- Create a subdir called
mac
- When that subdir is accessed, ssh as
btasker
tomac.home
and mount/Users/btasker
intomac
-
allow_other
tells autofs should allow other users to access the Mac - we use this because the service runs the mount as root - (Yes, I may have done all this to help avoid having to use the Mac keyboard)
Note that #
and :
are special characters in sshfs
configuration, and so need to be escaped.
We're not quite there yet, though. The actual mounting operation gets run as root
, and so it's root that needs to be able to SSH onto the target host.
sudo -i
ssh-keygen -b 4096
ssh-copy-id [user]@[targetbox] # e.g. btasker@mac.home
ssh [user]@[targetbox] # Verify that you get logged in
Finally, restart Autofs
systemctl restart autofs
And then verify that the mount works
ls ~/mounts/mac