There are several ways (loginhook, launchdaemon etc.) to automount a sparsebundle before logging in, but there's none without writing down the password in plaintext for automount an encrypted sparsebundle.
Reading out the password from the keychain requires to unlock it before, therefore it's not possible to automate the process without user action.
#!/usr/bin/env bash -e
# SOURCE: http://risponderetag.wpdev8.com/p/35966.html
SPARSEBUNDLE_PATH="/Users/Shared/username.sparsebundle"
SPARSEBUNDLE_MOUNT_PATH="/Users/username/"
KEYCHAIN_PATH="/Users/username/Library/Keychains/login.keychain"
# Check existing states
if [ -e "$SPARSEBUNDLE_MOUNT_PATH" ]; then
echo "Already mounted."
exit 0
fi
# The mount command uses security find-generic-password
# to get the password from the keychain store
MOUNT_PASSWORD=$(security find-generic-password -w -D "disk image password" -l username.sparsebundle $KEYCHAIN_PATH)
printf $MOUNT_PASSWORD | hdiutil attach -stdinpass -mountpoint "$SPARSEBUNDLE_MOUNT_PATH" "$SPARSEBUNDLE_PATH"
For further informations see:
Can I mount an encrypted image BEFORE Finder loads? http://techanic.net/2012/10/14/programmatically_mounting_encrypted_disk_images_in_os_x.html
Question (EDIT):
Are there other ways to pass a keychain password without using plaintext or user interaction?