How to add an encrypted private key with ssh-add via a script?

Host Key Not Cached Putty

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."





Discover More
Git Open Ssh
What is OpenSSH ssh-agent?

ssh-agent is the authentication agent of Openssh. It stores un/desencrypted private keys in memory, and communicates with SSH clients via Unix_domain_socket you don't get a ssh-agent Unix Socket...



Share this page:
Follow us:
Task Runner