ssh-agent needs to start each time on my server

The question was a bit unclear, so this answer may really for a different question. But since the answer may still prove useful to others, I think it is worthwhile keeping around.

When you type ssh-agent /bin/bash an instance of ssh-agent is started, which will keep running for as long as that shell is active. By default that ssh-agent will be used only by that shell, and it will terminate once you close that shell.

If instead you only type ssh-agent, an agent will be started in the background, which keeps running, even if you close the shell. The ssh-agent command will print commands on stdout, which can be typed in to start using that ssh-agent. You would have to type those commands each time.

You can start a background ssh-agent and start using it in the current shell by typing eval $(ssh-agent). However you would have to store the SSH_AUTH_SOCK environment variable somewhere and set it if you log in again.

With that background information in place, I have three suggestions as to how to go about always having the agent available.

  • Use a screen session on the server. When you start the screen type eval $(ssh-agent) ; screen, that agent will stay running on the server, and if you connect to that screen again later, it will still remember which agent to use.
  • Insert commands in your ~/.bash_profile file to find the active agent, if one exists and set the SSH_AUTH_SOCK environment variable.
  • Use ssh agent forwarding to use the agent on the client rather than one on the server. Make sure you understand the security implications of that, before you use it.

Finding the ssh-agent from ~/.bash_profile could be done with a script looking like this

#!/bin/bash

for P in /tmp/ssh-*/agent.*
do
    if [ -O "$P" ] && [ -O "$(dirname "$P")" ]
    then
        L=$(SSH_AUTH_SOCK="$P" timeout 1s ssh-add -l > >(wc -l))
        case $? in
            0)
                echo "$L $P"
                ;;
            1)
                echo "0 $P"
                ;;
        esac
    fi &
done | sort -rn | if read N P
then
    echo "SSH_AUTH_SOCK='$P'; export SSH_AUTH_SOCK"
else
    ssh-agent
fi

Which could be invoked from ~/.bash_profile like this eval $(find-agent) (assuming the script was named find-agent.)


An ssh command may fail with the error message Permission denied (publickey)., but work if you load the same key into an agent beforehand, if you have misconfigured the ssh client.

By default ssh and ssh-add will load keys from the same places, so either both will find the needed key, or neither will find it. However in /etc/ssh/ssh_config and ~/.ssh/config, you can override the path used by ssh through the IdentityFile setting.

If ~/.ssh/config contains an incorrect IdentityFile setting, you will see the symptoms described in your post.