74

I have two public keys, one for some servers and one for others. How do I specify which key to use when connecting to a server?

rid
  • 951
  • 1
  • 7
  • 11

3 Answers3

84

Assuming you're on a Unix/Linux environment, you can create or edit the file ~/.ssh/config.

That config file allows you to establish the parameters to use for each host; so, for example:

Host host1
  HostName <hostname_or_ip>
  IdentityFile ~/.ssh/identity_file1

Host Host2
  HostName <hostname_or_ip2>
  User differentusername
  IdentityFile ~/.ssh/identity_file2

Note that host1 and host2 can also be not hostnames, but rather labels to identify a server.

Now you can log onto the to hosts with:

ssh host1
ssh host2
Abdull
  • 187
  • 1
  • 14
Marco Bizzarri
  • 1,358
  • 1
  • 11
  • 11
  • 57
    You can also use `-i `, but I'd definitely recommend the config file method in the general case. – womble Jul 30 '11 at 08:43
  • I tried this but I keep getting prompted of the passphrase for my key. Even when I enter the passphrase correctly, the ssh login doesn't work. I tried using a blank passphrase too – Hamman Samuel Feb 29 '16 at 20:27
  • I had to do `ssh differentusername@host2` for a proper login, but otherwise this worked wonderfully, thank you! – agrippa Jun 21 '19 at 21:57
1

I explicitly mention the key during clone or pull or any git operations.

First you need to create key files with ssh-keygen command, then copy the .pub file to the host.

And during connecting, use the file without any extension.

Simple one liner

git -c core.sshCommand="ssh -i ~/.ssh/id1" pull
git -c core.sshCommand="ssh -i ~/.ssh/id1" clone <github>.git
-2

On Fedora 27, you can put the private/public keys under ~/.ssh/ and then when you ssh to a host, both of them will be tried automatically.

zhigang
  • 117
  • 4