Setting Up ssh-agent to Ask Passphrase Only Once

Short Version

ssh-agent bash



or maybe

ssh-add /home/user/.ssh/id_dsa

Long Version

Before trying anything, be sure that the communication between to the two hosts is using keys. Type this:

ssh target

you should see this:

Enter passphrase for key '/home/user/.ssh/id_rsa':


user@target's password:

If you get prompted for a passphrase instead of a password, go here, but be sure to add a passphrase. It is extremely dangerous to use a private key that doesn't have a passphrase. If anyone gets access to that private key, they can use it. However, adding a passphrase initially brings you back to the problem of asking for the passphrase several times. ssh-agent can fix this problem. To get started, simply type:

ssh-agent bash

This creates a new bash process that allows you to add private keys. When adding a new private key you will be prompted for the passphrase once and only once. Do that by typing:


Then, the key at ~/.ssh/id_dsa will be added and you should not get prompted for a passphrase. Then, type exit to have the OS forget your passphrase.

To verify that your key has been added, type:

ssh-add -l

It should show you the fingerprints and filenames of all keys in the agent session.

Using an ssh-agent in a script

Use the following bash code to reuse and ssh-agent in a script:

#Check for an existing ssh-agent
if [ -e $tempfile ]
    echo "Examining old ssh-agent"
    . $tempfile
#See if the agent is still working
ssh-add -l > /dev/null
#If it's not working yet, just start a new one.
if [ $? != 0 ]
    echo "Old ssh-agent is dead..creating new agent."
    #Create a new ssh-agent if needed
    ssh-agent -s > $tempfile
    . $tempfile
    #Add the key
#Show the user which keys are being used.
ssh-add -l

ssh-agent -s creates an ssh-agent and prints out three lines that basically set the appropriate environment variables for ssh-add to function properly. This script saves the output of ssh-agent -s to a known file location that can be reused each time the script is run. It also detects if the ssh-agent is no longer working. If so, it simply launches a new agent and adds the key.

The nice part about this script is that it will work if a script is sudo'd. However, the file will get a permission's error if the script is run with sudo and then run without sudo.

Your rating: None Average: 4.1 (16 votes)