2

I add the following in my .bashrc

ssh-add ~/.ssh/id_rsa

so when I open a new tab in my shell/terminal app (iTerm2 on macOS), it automatically add the SSH identity using the SSH agent and I don't need to manually type SSH password in that tab. But if I have many tabs, it seems to unnecessarily have many running instances of ssh-agent.

Is there a better way to achieve this?

  • 1
    One doesn't follow from the other. In now-usual setups, you have only one ssh-agent, created as part of the desktop session startup, and you don't have to re-add in each new terminal either. Can you elaborate on how you start your ssh-agent? – Ulrich Schwarz Nov 1 '17 at 17:41
  • 1
    At worst, this just performs an idempotent operation multiple times on the same agent. In fact, ssh-add won't do anything if there isn't an agent already running. – chepner Nov 1 '17 at 19:02
6

Your issue seems to be that you're starting a new invocation of the agent on each shell initialization (probably in your .bash_profile or .bashrc). This is not necessary, so you should find those ssh-agent calls and remove them.

On OSX, there is usually one ssh-agent started at boot time for your desktop session. For example:

myhost:~)-> ps -ef | grep ssh-agent
  501   986     1   0 10:18AM ??         0:00.14 /usr/bin/ssh-agent -l
  501  2126   736   0  5:30PM ttys007    0:00.00 grep ssh-agent

In order to access it, you need to find out where it's listening socket is, usually in /tmp/com.apple.launchd.<blah>/Listeners (where <blah> is some random alpha-numeric identifier. There are likely to be several, but you want the one that has the 'Listeners' socket in it).

Once you find it's socket, you can connect to it, using the standard SSH environment variable, SSH_AUTH_SOCK. For example:

myhost:~)-> export SSH_AUTH_SOCK=/tmp/com.apple.launchd.1h2j3k4l5/Listeners
myhost:~)-> ssh-add ~/.ssh/id_rsa
Enter passphrase for ~/.ssh/id_rsa: <typing_here>
Identity added: ~/.ssh/id_rsa (~/.ssh/id_rsa)

Once this is exported to the shell, one can, at this point, use the ssh-add command to provide his or her key passphrase and add a key to the agent. You can also see other options you might want to explore in the manual pages for the ssh-agent.

  • This is very on the spot to fix my issue on macOS. Now I want to do this to all my machines. What's the equivalent on (Ubuntu) Linux? – qazwsx Nov 4 '17 at 0:36
  • It's actually exactly the same, although the Listener file will be called something like /tmp/ssh-<blah>/agent.<pid>. Take a look at the ssh-agent manual page for more details. – Thomas N Nov 8 '17 at 16:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.