Skip to content

Instantly share code, notes, and snippets.

@faun
Last active July 8, 2020 10:50
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save faun/1c0ffb639b4ba419d07f to your computer and use it in GitHub Desktop.
Save faun/1c0ffb639b4ba419d07f to your computer and use it in GitHub Desktop.
Script to mount remote SMB volume using password stored in Mac OS keychain without needing admin or sudo priveliges
#!/usr/bin/env bash
# Fetch the password from the keychain if it exists
PASSWORD_ENTERED=false
ACCOUNT_NAME='login'
SERVICE_NAME='mount_volume'
PASSWORD=$(
security 2> /dev/null \
find-generic-password -w \
-a $ACCOUNT_NAME \
-s $SERVICE_NAME
)
# Stop the script from continuing if there's an error
set -e
# Remote file user
REMOTE_USER='video'
# Remote file server
REMOTE_SERVER='terraform.faun.me'
# Volumes to mount
declare -a REMOTE_MOUNTS=(Television Movies)
# Where to mount volumes
LOCAL_DESTINATION="$HOME/Mount/"
# Prompt for password if not in keychain
if [ -z $PASSWORD ]; then
echo "Enter the password for user ${REMOTE_USER} on ${REMOTE_SERVER}:"
read -s PASSWORD
PASSWORD_ENTERED=true
fi
# URL escape the password (allow for special characters in the password)
ENCODED_PASSWORD="$(
perl -MURI::Escape -e \
'print uri_escape($ARGV[0]);' \
"$PASSWORD"
)"
# Mount each volume from $REMOTE_MOUNTS to $LOCAL_DESTINATION
for MOUNT in ${REMOTE_MOUNTS[*]}
do
mkdir -p "$LOCAL_DESTINATION/$MOUNT"
mount_smbfs -o \
automounted \
-N "//${REMOTE_USER}:$ENCODED_PASSWORD@${REMOTE_SERVER}/${MOUNT}/" \
"$LOCAL_DESTINATION/$MOUNT"
done
# Save the password to the keychain if provided
if [ $PASSWORD_ENTERED != false ]
then
security add-generic-password \
-a $ACCOUNT_NAME \
-l "Volume mount password for user ${REMOTE_USER} on ${REMOTE_SERVER}" \
-s $SERVICE_NAME \
-w $PASSWORD
fi
@Brunnocampos1
Copy link

Just Solved. The problem was a double '/' on the address. My bad. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment