How to add an encrypted private key with ssh-add via a script?
About
ssh-add is an openssh command that adds a key to the ssh-agent.
By default, it will ask the passphrase for an encrypted private key, the script below shows you how to use SSH_ASKPASS to pass the passphrase automatically.
SSH_ASKPASS executable Script
PASSPHRASE=welcome
KEY_PATH=~/.ssh/id_rsa
# The instruction is in the man page. SSH_ASKPASS needs a path to an executable
# that emits the secret to stdout.
# See doc: https://man.archlinux.org/man/ssh.1.en#SSH_ASKPASS
SSH_ASKPASS="$HOME/.ssh/askpass.sh"
echo " - Creating the executable $SSH_ASKPASS"
PASSPHRASE=$(eval "echo \$$SSH_VAR_PREFIX$var")
printf "#!/bin/sh\necho %s\n" "$PASSPHRASE" > "$SSH_ASKPASS"
chmod +x "$SSH_ASKPASS"
TIMEOUT=5
echo " - Executing ssh-add (if the passphrase is incorrect, the execution will freeze for ${TIMEOUT} sec)"
# freeze due to SSH_ASKPASS_REQUIRE=force otherwise it will ask it at the terminal
timeout $TIMEOUT bash -c "DISPLAY=:0 SSH_ASKPASS_REQUIRE=force SSH_ASKPASS=$SSH_ASKPASS ssh-add $KEY_PATH" || >&2 echo " - Bad passphrase" ; exit 1
echo " - The key $KEY_PATH was added successfully the SSH agent."