How does ssh-agent understand which key should it use for which remote server?

I've came across different questions and posts that touches this topic somehow, but it still remain unclear to me.

What I have found is that if you want to use different ssh keys you need to use -i option and specify path to needed key or you can setup Identity files that specifies which key pair for which host to use.

But does it mean that by default ssh-agent can use only one key pair and it will try to use it for all remote servers?


But does it mean that by default ssh-agent can use only one key pair and it will try to use it for all remote servers?

By default, ssh-agent will use all the keys added to it to all the servers you connect. You can limit the keys by ssh_config as in the other answer.

The keys have fingerprints, but in the first phase of public key authentication, the public parts are just verified against the server list and if they do not match, authentication is skipped (usually to other key or password authentication).

  • 1
    To see this, run your SSH client with the -v verbose option. Apr 20 '16 at 16:03

SSH supports a ~/.ssh/config file that allows you to specify different keys for different hosts. So you could have

Host github.com
    IdentityFile ~/.ssh/github.key
Host example.com
    IdentityFile ~/.ssh/example.key

There's a good tutorial on this functionality here.


The 'key' (no pun intended) is based upon the fingerprint as specified in RFC4716. As explained in ssh's man page:

When connecting to a server for the first time, a fingerprint of the
server's public key is presented to the user (unless the option
StrictHostKeyChecking has been disabled).  Fingerprints can be determined
using ssh-keygen(1):

           $ ssh-keygen -l -f /etc/ssh/ssh_host_rsa_key

If the fingerprint is already known, it can be matched and the key can be
accepted or rejected.

In an ASCII nutshell here is fingerprinting explained with regards to which key is chosen/used:

ssh-keygen yourfingerprint
you ssh --> server (stores your fingerprint)
you ssh --> millions of other servers
you ssh initial server --> server --> Have I seen this fingerprint before?


Because I hit enter too prematurely, the fingerprints are stored in:

  • 1
    the start makes sense. The end does not answer the question in any point and is just nonsense.
    – Jakuje
    Apr 19 '16 at 21:46
  • 1
    This is about half correct for SSH server keys, but completely irrelevant to SSH client keys, which is the subject of this question. Apr 20 '16 at 4:50

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.