Skip to content

Instantly share code, notes, and snippets.

@maelcum
Created October 18, 2020 12:59
Show Gist options
  • Save maelcum/44567262acab0a4417078780aae04135 to your computer and use it in GitHub Desktop.
Save maelcum/44567262acab0a4417078780aae04135 to your computer and use it in GitHub Desktop.
request a password if not already saved, save password for later, and fetch it when necessary
...
# Prerequisites:
#
# Accessing Password
# To scan system directories the script needs elevated privileges. This means the user needs to input his password.
# To automate the running of this script, it accesses the Keychain.app for the password.
# For this to work, an entry has to be made in the Keychain.app manually:
# security add-generic-password -s '<identifier>' -a '<userid>' -w '<passwd>'
# or even better:
# security add-generic-password -s '<identifier>' -a '<userid>' -w '<passwd>' -j 'comment' -T /usr/bin/security -D 'Scriptpassword'
# where
# -s some identifier like device name, url, alias, whatever
# -a username to login into the device
# -w password for the userid to log into the device
# -j comment
# -T binaries that are allowed access
# -D type that better fits the use than "Internet Password"
# ex: security add-generic-password -s $HOSTNAME -a $LOGNAME -w 'P455w0rd' -j 'for Script: create_change_protocol_10.14.sh' -T /usr/bin/security -D 'Scriptpassword'
...
...
# --------------------------------------------------------------------------------------------------------------------
# FUNCTIONS
# --------------------------------------------------------------------------------------------------------------------
# ensure elevated privileges
fncEnsureElevatedPrivileges()
{
# check if users password has already been saved to 'Keychain Access.app' and if not, ask for it and save it
# remember: first set proper $HOSTNAME, then reboot, _then_ create keychain entry
if ! security find-generic-password -s "${HOSTNAME%%.*}" -w 2>/dev/null | sudo -Svp "" 2>/dev/null
then
echo; read -rsp "${colorRedInverted}please enter the password for user $LOGNAME${colorNone} " userPasswd; echo
echo -e "${statusInfo} create Keychain Access.app entry for user${colorNone}"
security add-generic-password -s "${HOSTNAME%%.*}" -a "$LOGNAME" -w "$userPasswd" -j 'for Shellscripts' -T /usr/bin/security -D 'Scriptpassword'
echo "$userPasswd" | sudo -Svp ""
fi
}
...
...
# --------------------------------------------------------------------------------------------------------------------
# MAIN
# --------------------------------------------------------------------------------------------------------------------
fncEnsureElevatedPrivileges
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment