How to connect to the same host with different SSH keys?
Jim Zandueta
Posted on August 16, 2022
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
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
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
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
Using the configuration file above, we can clone repositories from your personal Github account with:
$ git clone git@github_personal:tonystark/ultron.git
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
-
Resources
Posted on August 16, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.