I am trying to add a key to ssh-agent
and want ssh-add
to read the password from the key file I'm using. How is this possible?
How do I automate this process from the shell script?
Adding or replacing a passphrase for an existing key To change your passphrase, you can simply run the ssh-keygen -p command. Specify the location of your current key, and input any old or new passphrases. There is no need to regenerate keys.
Using passphrases increases the security when you are using SSH keys. Using a key without a passphrase can be risky. If someone obtains a key (from a backup tape, or a one-time vulnerability) that doesn't include a passphrase, the remote account can be compromised.
SSH passphrases protect your private key from being used by someone who doesn't know the passphrase. Without a passphrase, anyone who gains access to your computer has the potential to copy your private key. For example, family members, coworkers, system administrators, and hostile actors could gain access.
Depending on your distribution and on the version of ssh-add you may be able or not to use the -p
option of ssh-add that reads the passphrase from stdin in this way:
cat passfile | ssh-add -p keyfile
If this is not working you can use Expect, a Unix tool to make interactive applications non-interactive. You'll have to install it from your package manager.
I have written a tool for you in expect. Just copy the content in a file named ssh-add-pass and set executable permissions on it (chmod +x ssh-add-pass
). You can also copy it to /usr/bin or /usr/local/bin to be accessible from the $PATH search.
#!/bin/bash if [ $# -ne 2 ] ; then echo "Usage: ssh-add-pass keyfile passfile" exit 1 fi eval $(ssh-agent) pass=$(cat $2) expect << EOF spawn ssh-add $1 expect "Enter passphrase" send "$pass\r" expect eof EOF
The usage is simply: ssh-add-pass keyfile passfile
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With