Linux – Tell ssh to try all key files in ~/.ssh/

linuxsshssh-keys

I have multiple keys in my ~/.ssh/ directory, each with a separate project name, for projects that have multiple servers each. id_rsa_project1, id_rsa_project2

However, ssh won't search for them. If I run ssh -v user@projectserver I get output like the following:

...
debug1: Connection established.
...
debug1: Authentications that can continue: publickey,password,keyboard-interactive
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /home/me/.ssh/id_rsa
debug1: Authentications that can continue: publickey,password,keyboard-interactive
debug1: Trying private key: /home/me/.ssh/id_dsa
debug1: Trying private key: /home/me/.ssh/id_ecdsa
debug1: Trying private key: /home/me/.ssh/id_ed25519
debug1: Next authentication method: keyboard-interactive
debug1: Authentications that can continue: publickey,password,keyboard-interactive
debug1: Next authentication method: password
user@projectserver password: 

This appears to be by design, as the ssh_config manpage says that, by default, the Identities searched for are ~/.ssh/id_dsa, ~/.ssh/id_ecdsa,
~/.ssh/id_ed25519 and ~/.ssh/id_rsa.

Of course, I can:

  • add the -i ~/.ssh/id_rsa_project1 switch to the command line each time, or
  • add IdentityFile ~/.ssh/id_rsa_project1 to a specification against the server in ~/.ssh/config, or
  • add IdentityFile ~/.ssh/id_rsa_project1 to /etc/ssh/ssh_config for each project.

…but all these seem too cumbersome for the regularity with which we change keys and key files.

I did try to add IdentityFile ~/.ssh/* to /etc/ssh/ssh_config but it appears to take it as a literal * rather than a wildcard.

How can I tell ssh to read and try all key files in ~/.ssh/ ?

Best Answer

The easiest way is to add them to ssh-agent:

Start agent:

eval `ssh-agent`

Add all keys in ~/.ssh:

ssh-add ~/.ssh/id_rsa_*

But note that it is not ideal way, since all the keys are tried on all the servers where you want are connecting. Proper configuration in ~/.ssh/config is advised solution.

Related Question