3

I have three SSH key pairs that I want to have added to the SSH agent every time I start a shell. After restarting I always have to manually add them again by using ssh-add <path_to_private_key>.

How can I do this?

2 Answers2

2

It depends.

If you log in through SSH, you can use SSH agent forwarding, by way of the -A option to ssh (alternatively, you can set an option in your ~/.ssh/config). Doing this will allow you to copy SSH keys from the server to your locally-running ssh-agent.

If you log in through an X session, you should have a single, central ssh-agent running, set up by your distribution. If not, make sure your ~/.xsession (or whatever you use to start your X session) contains something like this:

ssh-agent awesome

(on the assumption that you're like me and love the awesome window manager).

If all else fails, you could use your ~/.bash_profile. In there, add something along the following lines (near the top of that file):

if [ -z "$SSH_AGENT_PID" ]
then
    exec ssh-agent bash
fi
ssh-add ...

this checks if you've already got an agent running; if not, it starts one anew, which then starts a shell. If you do, it adds your keys to it.

(There is another option where you run eval ssh-agent without passing it a command to run. Don't do this; it is less secure)

-1

After starting the agent save the commands to set the SSH_AUTH_SOCK and SSH_AGENT_PID to a file. Then execute these commands instead of starting the agent again. This will leave you with one shared agent for all your shells. Building this functionality in your .profile or .bash_profile file will make this easier.

If you are working in an X-Windows environment, you could just start the agent as part of the X-Windows initialization. Your shells should then inherit the existing agent settings.

When using this solution, I add the keys with a relatively short timeout. The default can be set when starting ssh-agent by using the -t option.

BillThor
  • 8,965
  • having a shared agent for shells who don't share a parent is a bad idea, and there's a simpler solution. – Wouter Verhelst Apr 07 '16 at 14:57
  • @WouterVerhelst As it is trivial to steal access to an ssh-agent running as the same user on the same server, I don't see any additional risk. – BillThor Apr 08 '16 at 03:31