Straight forward way to run ssh-agent and ssh-add on login via SSH?

I'm trying to have the following commands be auto-executed when I login to my server via ssh:

ssh-agent /bin/bash
ssh-add ~/.ssh/id_rsa

My ssh key has a passphrase and I'm fine with entering it once per login.

I tried putting this in my .bashrc file, however I believe that ssh-agent starts a new bash session. When I try to login after having this in my .bashrc, it gets stuck, and I have to type 'exit' to then see the 'enter passphrace to unlock key' prompt

Any other suggestions?

Server is running Ubuntu LTS


You can try adding this:

eval $(ssh-agent -s)
ssh-add ~/.ssh/id_rsa

This way the ssh-agent does not start a new shell, it just launches itself in the background and spits out the shell commands to set the appropriate environment variables.

As said in the comment, maybe you do not want to run the agent at all on the remote host, but rather on the box you are working from, and use

ssh -A remote-host

to forward the services of your local ssh agent to the remote-host.

For security reasons you should only use agent forwarding with hosts run by trustworthy people, but it is better than running a complete agent remotely any time.


Another alternative is to add this to your .bashrc. This has the same advantage as Erik's answer (ensuring a single instance) but doesn't require an additional package.

# SSH Agent should be running, once
runcount=$(ps -ef | grep "ssh-agent" | grep -v "grep" | wc -l)
if [ $runcount -eq 0 ]; then
    echo Starting SSH Agent
    eval $(ssh-agent -s)
fi

This runs ssh-add if there is not at least 1 key loaded and sets a key timeout of 1 day:

ssh-add -l &>/dev/null
if ! [ "$?" == 0 ]; then
     echo Adding keys...
     ssh-add -t 1d
fi

One alternative is to use Funtoo's Keychain. Then you can stick this one-liner in your bash shell:

eval $(keychain --eval id_rsa)

That does the same thing (launches ssh agent, etc.), while also not running an ssh-agent process for each subshell. Instead it looks for "already running" instances you own and attaches you to them.


Also keep in mind if you have ssh connection keep-alive you need to delete existing connection files before -A takes effect. Delete any ssh connection files in /tmp/[host].