DEV Community

Jim Zandueta
Jim Zandueta

Posted on • Updated on

How to connect to the same host with different SSH keys?

Required Reading:

Optional Reading:

  • None

-

Setup your SSH configuration file

When connecting to a remote server via SSH, we would use the command line to specify the remote user name, hostname, and port, as shown below:

$ ssh tony@avengers.com -p 4321
Enter fullscreen mode Exit fullscreen mode

We can connect to the server using the same options as in the previous command by typing ssh avengers after adding the following lines to your ~/.ssh/config:

Host avengers
    HostName avengers.com
    User tony
    Port 4321
Enter fullscreen mode Exit fullscreen mode

We can also specify which SSH key to use when connecting to a specific server in the configuration file by setting IdentityFile:

Host avengers
    HostName avengers.com
    User tony
    Port 4321
    IdentityFile ~/.ssh/id_rsa_avengers

Host marvel
    HostName marvel.com
    User tony
    Port 8080
    IdentityFile ~/.ssh/id_rsa_marvel
Enter fullscreen mode Exit fullscreen mode

The use of IdentityFile is especially useful when connecting to the same hostname with different SSH keys. A real-world example would be having multiple Github accounts, such as personal and work:

Host github_personal
    HostName github.com
    IdentityFile ~/.ssh/github_personal

Host github_work
    HostName github.com
    IdentityFile ~/.ssh/github_work

IdentityFile ~/.ssh/id_rsa 
#default ssh key to use for all other hosts
Enter fullscreen mode Exit fullscreen mode

Using the configuration file above, we can clone repositories from your personal Github account with:

$ git clone git@github_personal:tonystark/ultron.git
Enter fullscreen mode Exit fullscreen mode

Notice that instead of @github.com as the host name, we use @github_personal as defined in the configuration file.

-

Updating the configuration file:

  • Open your favorite terminal
  • Create/Open the SSH configuration file
$ nano ~/.ssh/config
Enter fullscreen mode Exit fullscreen mode

-

Resources

Top comments (2)

Collapse
 
ccoveille profile image
Christophe Colombier

I found one typo

ssh ... -p 1234

Then

Port 4321

As you are repeating Port 4321, you should fix ssh -p 4321

Collapse
 
jimzandueta profile image
Jim Zandueta

Thanks for the catch! 😄