Bash Helper Scripts for Mounting and Unmounting SSH/SFTP drives


These are the helper scripts I use to set up SSH mountpoints.

Usage:

# mounts someguy's home directory (/home/someguy) at
#   somesite.com to local mountpoint ~/mnt/sshfs/somesite.com
mount-sshfs.sh someguy somesite.com
# unmounts somesite.com
umount-sshfs.sh somesite.com


We’ll need sshfs for this one…

sudo apt-get install sshfs

This script, mount-sshfs.sh, mounts the SSH/SFTP connection:

#!/bin/bash
USERNAME=$1
SITENAME=$2
BASEDIR=${HOME}/mnt/sshfs
if [ -z "$1" -o -z "$2" ] ; then
        echo Usage:
        echo "  $0 USERNAME SITENAME.COM"
        echo
        exit 1;
fi
if [ -e $BASEDIR/$SITENAME/ ] ; then
        echo Mount-point found.  Re-mounting..
        umount-sshfs.sh $SITENAME
fi
if [ ! -d $BASEDIR/$SITENAME/ ] ; then
        mkdir -p $BASEDIR/$SITENAME/
fi
echo
echo Mounting $SITENAME on $BASEDIR/$SITENAME/
sshfs -o workaround=rename $USERNAME@$SITENAME:/home/$USERNAME/ $BASEDIR/$SITENAME/ $3 $4

And this one, umount-sshfs.sh, unmounts it:

#!/bin/bash
SITENAME=$1
BASEDIR=${HOME}/mnt/sshfs
if [ -z "$1" ] ; then
        echo Usage:
        echo "  $0 SITENAME.COM"
        echo
        exit 1;
fi
if [ ! -d $BASEDIR/$SITENAME/ ] ; then
        echo Not mounted.
        exit 1
fi
echo
echo Un-mounting $SITENAME...
fusermount -u $BASEDIR/$SITENAME/
rmdir $BASEDIR/$SITENAME/

And if the SSH connection ever hangs, you may need to forcefully unmount it. That’s what
force-umount-sshfs.sh is for. Note, you’ll need to run this as sudo!

#!/bin/bash
SITENAME=$1
BASEDIR=${HOME}/mnt/sshfs
if [ -z "$1" ] ; then
        echo Usage:
        echo "  $0 SITENAME.COM"
        echo
        exit 1;
fi
if [ ! -d $BASEDIR/$SITENAME/ ] ; then
        echo Not mounted.
        exit 1
fi
echo
echo Un-mounting $SITENAME...
killall sshfs
umount -l $BASEDIR/$SITENAME
rmdir $BASEDIR/$SITENAME/