Skip to content

Instantly share code, notes, and snippets.

@j4Hu
Forked from lordtangent/auto.sshfs
Last active June 5, 2024 08:34
Show Gist options
  • Select an option

  • Save j4Hu/78cf2b06b839e824f29ad78c3a967451 to your computer and use it in GitHub Desktop.

Select an option

Save j4Hu/78cf2b06b839e824f29ad78c3a967451 to your computer and use it in GitHub Desktop.
universal sshfs Automount

Universal sshfs automount setup

This gist requires autofs and sshfs be installed on your system. You must have ssh access to each host you would like to automount via a passwordless ssh key.

The script currently expects a the key to be named $HOME/.ssh/id_ed25519 but you can change it if you like.

Install Packages (deb)

apt-get -y install sshfs autofs

Install Script

mkdir /etc/auto.master.d/
echo '/net/sshfs     /etc/auto.sshfs' > /etc/auto.master.d/ssh.autofs

egrep '^\+dir:/etc/auto.master.d' /etc/auto.master || \
echo 'dir:/etc/auto.master.d' >> /etc/auto.master

wget -O /etc/auto.sshfs \
  "https://gist.githubusercontent.com/j4Hu/78cf2b06b839e824f29ad78c3a967451/raw/63c1b431e9d36ef7c9b342c54330c7cdf5773c73/auto.sshfs" 
  
chmod 755 /etc/auto.sshfs
systemctl restart autofs

Test

trigger to the automount of the remote host by going to /net/sshfs/username@hostname

#!/bin/bash
#
# /etc/auto.sshfs automount script
# This file must be executable to work! ( chmod 755 )
#
# PARENT: https://gist.github.com/lordtangent/0092643428b42c796415df2a20bc3861#file-auto-sshfs
IDMAP_CREATE="no"
DIR_CONF="/etc/sshfs"
SSH_KEY_NAME="id_ed25519"
key="${1/%:/}"
user="${key/@*/}"
t="${key/*@/}"
server="${t/:*/}"
tp="${t/*:/}"
port="${tp/\/*/}"
if [ $port = $server ]; then
port=22
fi
mountopts="-fstype=fuse,rw,nodev,noatime,allow_other,port=${port}"
mountopts+=",StrictHostKeyChecking=no,IdentityFile=/home/${user}/.ssh/${SSH_KEY_NAME}"
if [[ -f "$DIR_CONF/$server/uidfile" ]]; then
if [[ -f "$DIR_CONF/$server/gidfile" ]]; then
mountopts+=",idmap=file,uidfile=$DIR_CONF/$server/uidfile"
mountopts+=",gidfile=$DIR_CONF/$server/gidfile"
elif [[ "$IDMAP_CREATE" == "yes" ]]; then
if [[ $(find $DIR_CONF/$server/uidfile -mtime +7 -print 2>&1 ) ]]; then
mkdir -p $DIR_CONF/$server
ssh -p $port -i /home/${user}/.ssh/$SSH_KEY_NAME ${user}@${server} 'cat /etc/passwd | cut -d ":" -f1,3' > $DIR_CONF/$server/uidfile
ssh -p $port -i /home/${user}/.ssh/$SSH_KEY_NAME ${user}@${server} 'cat /etc/group | cut -d ":" -f1,3' > $DIR_CONF/$server/gidfile
fi
fi
fi
echo "$mountopts :sshfs#${user}@${server}:/"
# /etc/auto.master.d/sshfs.autofs
# /net/sshfs needs to exist to trigger this rule!
/net/sshfs /etc/auto.sshfs --timeout=60
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment