Last Updated: February 25, 2016
·
1.865K
· diurnalist

Automatically add ssh keys to agent on shell login

If you have a few ssh keys you use for various servers, you can manage them in many ways. One way is to add them to your ssh-agent via ssh-add path/to/key. However, you have to remember to do this every time you log in.

In my case, I had all of my keys located in a ~/.ssh/keys folder. By iterating over the list of private keys (which don't end in .pub), and ssh-add'ing each one, your ssh agent is fully primed on login. I added this to my .bash_profile:

find ~/.ssh/keys -not -name '*.pub' -type f | xargs ssh-add

If you have passcodes on your ssh keys you'll be prompted to enter them. However, on Mac OS X, your login scripts will run any time a new terminal window is opened, so you end up typing your passcodes over and over. By comparing the list of known keys with the list of keys already found in your ssh-agent (using comm), you can ensure that you only have to enter your passcodes one time.

comm -3 \
  <(ssh-add -l | sed -n '/no identities/!p' | cut -d' ' -f3) \
  <(find ~/.ssh/keys -not -name '*.pub' -type f) \
  | xargs ssh-add

Final note: if you're using Mac OS X, you can also just use the -K flag when calling ssh-add, which will persist your keys to your user Keychain. In my case, I wanted to know how to solve the problem without storing my keys anywhere else where they could be potentially compromised.