I have to make several updates and fixes to my guide, but for those who are waiting, here is the updated script that should work whether it is run as root or as a normal user, with the important caveat that in order to run as root, you must give each fstab entry an owner with the option uid=yourusername. For fstab entries without this option, this script will function identically to the previous one.
Also, this is exactly the script I am using. I have not yet attempted to make the comments intelligible to anyone but myself. That's one thing I intend to do before adding this script to my guide.
Code:
#!/bin/sh
isa_number () {
! echo $1 | egrep -q '[^0-9]'
return $?
}
user_from_uid () {
# we need a number
if ! isa_number $1
then
return 1
fi
local IFS=":"
while read name x uid the_rest
do
if [ "$1" -eq "$uid" ]
then
echo "$name"
return 0
fi
done </etc/passwd
return 1
}
# Not for loopback
[ "$IFACE" != "lo" ] || exit 0
# comment this for testing
exec &>/dev/null # squelch output for non-interactive
# unmount them first
mounted=`grep 'sshfs#' /etc/mtab | awk '{ print $2 }'`
[ -n "$mounted" ] && umount -l $mounted
while read fs mp type opts dump pass extra
do
# check validity of line
if [ "`expr substr ${fs}x 1 1`" = "#" -o -z "$pass" -o -n "$extra" ]; then
# line is a invalid or a comment
continue
# check if the line is an sshfs line
elif echo $opts | grep -q 'comment=sshfs'; then
#find out the user
mp_uid=`echo $opts | egrep -o 'uid=\w+'` # "mp" stands for mount point
if [ -z "$mp_uid" ]; then
# no uid was specified, so just try to mount as the current user
mount $mp
else
mp_uid_length=`expr length $mp_uid - 3`
mp_uid=`expr substr $mp_uid 5 $mp_uid_length` # delete the "uid="
# mp_uid now contains either a username or a uid
# convert to username if possible; otherwise assume that it already is one
if ! mp_user=`user_from_uid $mp_uid`; then
mp_user=$mp_uid
fi
# mp_user is either a username or an invalid uid; either way is ok
if [ "$mp_user" = "`whoami`" ]; then
# current user owns the mount, so mount normally
mount $mp
elif [ "`whoami`" = "root" ]; then
# running as root, so su to user and mount
su $mp_user -c "mount $mp"
fi
# otherwise, don't try to mount another user's mount point
fi
fi
# if not an sshfs line, do nothing
done </etc/fstab
Bookmarks