How do I configure SSH so it doesn't try all the identity files automatically?

I have been putting my ssh identity files inside my ~/.ssh/ folder. I have probably about 30 files in there.

When I connect to servers, I will specify the identity file to use with something like

ssh -i ~/.ssh/client1-identity [email protected]

However, if I do not specify an identity file, and just use something like this:

ssh [email protected]

I get the error

Too many authentication failures for user123

I understand that is because if no identity file is specified, and ssh can find identity files, then it will try all of them.

I also understand that I can edit the ~/.ssh/config file and specify something like:

Host example.com
PreferredAuthentications keyboard-interactive,password

in order to prevent that connection from trying known identity files.

So, I guess I could move my identity files outside of the ~/.ssh/ directory, or I could specify each host that I want to disable identity-file authentication for in the config file, but is there any way to tell SSH by default not to search for identity files? Or to specify the ones it will search for?


You can use the IdentitiesOnly=yes option along with IdentityFile (see ssh_config man page). That way, you can specify which file(s) it should look for.

In this example, ssh will only look in the identities given in the ssh_config files + the 4 ones listed on the command line (the identities provided by the agent will be ignored):

ssh -o IdentitiesOnly=yes \
    -o IdentityFile=id1.key \
    -o IdentityFile=id2.key \
    -i id3.key \
    -i id4.key \
    [email protected]

The forms -i and -o IdentityFile= are interchangeable.

In .ssh/config, you can include config like this:

Host example
User user123
Hostname example.com
IdentityFile ~/.ssh/id_rsa_example
IdentityFile ~/.ssh/id_rsa_example2
IdentitiesOnly yes

user76528's short answer is correct, but I just had this problem and thought some elaboration would be useful. You might also care about this solution if you've wondered "Why is ssh ignoring my identityfile configuration option"?

Firstly, unlike every other option in ssh_config, ssh does not use the first IdentityFile that it finds. Instead the IdentityFile option adds that file to a list of identities used. You may stack multiple IdentityFile options, and the ssh client will try them all until the server accepts one or rejects the connection.

Second, if you use an ssh-agent, ssh will automatically try to use the keys in the agent, even if you have not specified them with in ssh_config's IdentityFile (or -i) option. This is a common reason you might get the Too many authentication failures for user error. Using the IdentitiesOnly yes option will disable this behavior.

If you ssh as multiple users to multiple systems, I recommend putting IdentitiesOnly yes in your global section of ssh_config, and putting each IdentityFile within the appropriate Host subsections.