Home > bash, debian > Mount / unmount sshfs as network goes up / down

Mount / unmount sshfs as network goes up / down

You can use sshfs to mount directories from a file server into your local filesystem. This is usually simpler than cifs or nfs mounts.

You need ssh logins without password and the sshfs package:
sudo apt-get install sshfs

The scripts below ensure automatic mounting and unmounting as your network comes up or goes down. Use chmod ugo+x to make sure they are executable.

/etc/network/if-up.d/mount-sshfs

#! /bin/sh

cd /home

for user in *; do
  script="/home/$user/.sshfs/mount.sh"
  if [ -x "$script" ]; then
    su $user -c "$script"
  fi
done

/etc/network/if-down.d/unmount-sshfs

#! /bin/sh

OLDIFS=$IFS
IFS='
'

for mount in $(mount | grep " type fuse.sshfs "); do
  dir=$(echo $mount | cut -f3 -d' ')
  userid=$(echo $mount | grep -o "user_id=[0-9]*" | cut -f2 -d'=')
  user=$(getent passwd $userid | cut -f1 -d':')
  su $user -c "fusermount -u $dir"
done

IFS=$OLDIFS

If you use the network-manager package, also symlink the script from if-post-down.d:

cd /etc/network/if-post-down.d
sudo ln -s ../if-down.d/unmount-sshfs

$HOME/.sshfs/mount.sh

For each user, this script may contain 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 users 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:

mkdir $HOME/.sshfs
vim $HOME/.sshfs/mount.sh
chmod ugo+x $HOME/.sshfs/mount.sh

On Debian, each of the actual users who will also has to be in the “fuse” group:
sudo adduser oliver fuse

The following is just an example taken from my desktop and laptop at home. We use an Excito Bubba/2 mini server that hosts shared storage for the whole family (/home/storage) and backup space for personal files (/home/oliver). I mount each of those server locations locally under /home/oliver/bubba.

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 to ensure that “oliver” on the server is mapped to the local “oliver” (idmap=user):

#! /bin/sh

sshfs -o ro oliver@bubba:/home/storage ~/bubba/storage
sshfs -o rw -o idmap=user oliver@bubba:/home/oliver ~/bubba/oliver
Advertisements
Categories: bash, debian
  1. No comments yet.
  1. No trackbacks yet.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: