How to use password from keychain for login into server in automator?

I'm using Big Sur and I want to create an app using Automator and run it as login items.

I add 'run shell script' in Automator and add this command:

mount_smbfs //[email protected]/shared_folder /Users/me/Desktop/myfolder

I want to fetch the password from keychain to log into the server. How can I do this? I don't want to expose the password in my script like using:

//user:pass@server/

Solution 1:

You can try adding a generic password entry to the keychain and then reading it into a variable using the security command. For example:

PASSWORD=`/usr/bin/security find-generic-password -l "Name of my password entry" -w`
mount_smbfs //user:[email protected]/shared_folder Users/me/Desktop/myfolder

The -l searches by label, the string immediately afterwards is the name you see in Keychain Access. The -w makes it print just the password.

The first time you do this you'll get prompted whether to allow reading the password. Click on "Always allow" to avoid future prompts. This solution is not very secure (the password will appear in the process list while mount_smbfs is running; not sure whether it's going to appear in the output of mount once the share was mounted) but at least better than hard-coding the password into the script.