Mount/unmount sshfs as network goes up/down

You can use sshfs to mount directories from a file server into your local filesystem. When client and server OS is Linux, this is usually simpler than cifs or nfs mounts.

You need ssh logins without password (using an ssh agent) and the sshfs package:

sudo apt install sshfs

I use two bash scripts to ensure automatic mounting and un-mounting as my network comes up or goes down, especially when using wifi :

Copy the scripts to the following paths (or create symlinks) and use chmod ugo+x to make sure they are executable:

  • /etc/network/if-up.d/mount-sshfs
  • /etc/network/if-post-down.d/unmount-sshfs

If you use NetworkManager you might have to enable and start its dispatcher service:

sudo systemctl enable NetworkManager-dispatcher.service
sudo systemctl start NetworkManager-dispatcher.service

On Debian there is a system script that automatically translates NetworkManager events to ifupdown events:

/etc/NetworkManager/dispatcher.d/01-ifupdown

With the dispatcher and the translater script in place, our mount/unmount scripts will be executed as desired.

User script

Every user who wants to use the mechanism we have set up so far needs to have a personal shell script at

$HOME/.sshfs/mount.sh

For each user, this script contains the sshfs invocations that the user wants to be auto-executed. It will be invoked automatically from /etc/network/if-up.d/mount-sshfs using the user’s permissions. Users who don’t need sshfs mounts, simply don’t create the file at all.

It is up to the individual user to create this file and make it executable.

Here is an example that works well with gnome-keyring as ssh-agent:

#!/bin/bash

# expose env vars for gnome-keyring ssh-agent:
export SSH_AUTH_SOCK="/run/user/$(id -u)/keyring/ssh"
export SSH_AGENT_PID="$(pgrep -f /usr/bin/ssh-agent)"

# if the ssh agent is running:
if [ -n "$SSH_AGENT_PID" ]; then
  sshfs -o idmap=user,ro bubba:/opt/data /home/oliver/hosts/bubba/data
  sshfs -o idmap=user tc: /home/oliver/hosts/tc
fi

We use an Excito Bubba/2 mini server that hosts shared storage for the whole family (bubba:/opt/data) and a little ThinkCentre server where I have a user account (tc:). I mount each of those server locations locally under /home/oliver/hosts.

I mount the shared storage read-only to prevent accidental data loss (-o ro) and my personal files as read-write (-o rw), with ownership mapping by username (idmap=user) to ensure that “oliver” on the server is mapped to the local “oliver”.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s