Skip to content

Instantly share code, notes, and snippets.

@selvanair
Last active June 16, 2020 01:14
Show Gist options
  • Save selvanair/dc08d04f5a2139cd74c65d3e1e2d8d76 to your computer and use it in GitHub Desktop.
Save selvanair/dc08d04f5a2139cd74c65d3e1e2d8d76 to your computer and use it in GitHub Desktop.
SMB share mount script for tunnelblick
#!/usr/bin/env bash
# Tunnelblick script to be run when CONNECTED (connected.sh)
# to mount SMB shares defined in $SHARES on User's Desktop.
# Will prompt for password during the first run.
#
# Selva Nair Jun 14, 2020
# BEGIN Settings
ORG='Example Inc.' # shown in password prompt
SHARES='folder1 folder2' # space separated list fo shares to mount
SERVER=fs.example.com # file server hosting the shares (or domain in case of DFS)
RUSER='userA' # remote username
DEST="/Users/$USER/Desktop" # shares will be mounted at $DEST/$SHARE
status=0 # on error we exit with this status -- set to 0 to fake success
# END settings
readkeychain() { # args: service account
service=${1:-"Unknown"}
account=${2:-"Unknown"}
echo -n $(security find-generic-password -w -a "$account" -s "$service")
}
getpassword() { # args: prompt
prompt=${1:-"Input password for file server"}
if [[ "$USER" != "" ]]; then
uid=$(id -u "$USER")
launchctl asuser $uid /usr/bin/osascript <<-EOF
text returned of (display dialog "$prompt" default answer "" buttons {"OK"} default button "OK" with hidden answer)
EOF
else
exit $status
fi
}
# get the password from the keychain
SERVICE="$SERVER"
ACCOUNT="$RUSER"
PASSWORD=$(readkeychain "$SERVICE" "$ACCOUNT")
if [ -z "$PASSWORD" ]; then
echo "No password in key chain -- prompt user and add it to the key chain"
PASSWORD=$(getpassword "Input password for $RUSER on $ORG server $SERVER")
if [[ -z "$PASSWORD" ]]; then
exit $status
fi
security add-generic-password -w "$PASSWORD" -a "$ACCOUNT" -s "$SERVICE" -U
fi
success=0
for SHARE in ${SHARES}
do
su "$USER" -c "mkdir -p \"$DEST/$SHARE\""
su "$USER" -c "\
/usr/bin/mount -t smbfs -o automounted,soft \"//${DOMAIN};${RUSER}:$PASSWORD@${SERVER}/$SHARE\" \
\"$DEST/$SHARE\"\
"
if [[ $? != 0 ]]; then # mount failed -- delete the mount point if empty
su "$USER" -c "rmdir \"$DEST/$SHARE\""
else
success=1
fi
done
# if no mounts succeeded password might have changed -- delete it from keychain
if [[ $success == 0 ]]; then
echo "mount failed -- possibly password chanaged? -- deleting password in keychain"
security delete-generic-password -s "$SERVICE" -a "$ACCOUNT"
fi
if [[ $success == 1 ]]; then
status=0
fi
exit $status
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment