Last updated on August 22, 2020 by Dan Nanni
If you connect to a remote server via SSH, which only accepts key authentication, you need to present your private key to the SSH server for authentication. It is straightforward to do so by using SSH's command line option. But what if you have many different servers, each of which happens to require different private keys? It will be nice for you to be able to automatically load a certain private key with a specific SSH server. In the following, I describe how to do it.
To specify a private key file in SSH from the command line, you can simply use
-i option in the
Assume that you want to access
ec2-23-22-230-24.compute-1.amazonaws.com with a private key located in
$ ssh -i ~/.ssh/alice.pem [email protected]
However, things get complicated when you have multiple private keys. In that case, you can declare which private key to use for each SSH server, in your SSH configuration file which is found at
$ vi ~/.ssh/config
Host ec2-23-22-230-24.compute-1.amazonaws.com IdentityFile ~/.ssh/alice.pem Host ec2-33-01-200-71.compute-1.amazonaws.com IdentityFile ~/.ssh/alice_v2.pem . . .
Then you can SSH without explicitly specifying your private key with
$ ssh [email protected]
Note that the hostname (e.g.,
ec2-23-22-230-24.compute-1.amazonaws.com) specified with
ssh command must match with that declared in
.ssh/config. Thus even with the above
.ssh/config, you cannot directly SSH to alternative names (e.g., IP address or hostname alias defined in
/etc/hosts) of the SSH server, unless you also add them explicitly to
188.8.131.52 is the IP address of
ec2-23-22-230-24.compute-1.amazonaws.com, and "
my_ec2_host 184.108.40.206" is added in
/etc/hosts. Then these alternative names must be declared in
~/.ssh/config as well in order you to use these names to connect to via SSH.
Host ec2-23-22-230-24.compute-1.amazonaws.com IdentityFile ~/.ssh/alice.pem Host 220.127.116.11 IdentityFile ~/.ssh/alice.pem Host my_ec2_host IdentityFile ~/.ssh/alice.pem
Then, all the following will work.
$ ssh [email protected] $ ssh [email protected] $ ssh [email protected]_ec2_host
Please note that this article is published by Xmodulo.com under a Creative Commons Attribution-ShareAlike 3.0 Unported License. If you would like to use the whole or any part of this article, you need to cite this web page at Xmodulo.com as the original source.