If you ssh to a remote server 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 to be able to automatically load a certain private key with a specific ssh server. Here is how.
To specify a private key file in ssh, you can simply use "-i" option in ssh. Assume that you want to access ec2-23-22-230-24.compute-1.amazonaws.com with private key located in ~/.ssh/alice.pem.
However, things get complicated when you have multiple private keys. In this case, you can declare which private key to use for a given ssh server, in a separate ssh configuration file named ~/.ssh/config.
Host ec2-23-22-230-24.compute-1.amazonaws.com IdentityFile ~/.ssh/alice.pem
Then you can ssh without explicitly specifying your private key with -i option.
Note that when you ssh, 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 ~/.ssh/config.
Suppose 220.127.116.11 is the IP address of ec2-23-22-230-24.compute-1.amazonaws.com, and "my_ec2_host 18.104.22.168" is in /etc/hosts. Then these alternative names must be declared in ~/.ssh/config as follows.
Host ec2-23-22-230-24.compute-1.amazonaws.com IdentityFile ~/.ssh/alice.pem Host 22.214.171.124 IdentityFile ~/.ssh/alice.pem Host my_ec2_host IdentityFile ~/.ssh/alice.pem
Then, all the following will work.
$ ssh firstname.lastname@example.org
$ ssh alice@my_ec2_host
Subscribe to Xmodulo
Do you want to receive Linux FAQs, detailed tutorials and tips published at Xmodulo? Enter your email address below, and we will deliver our Linux posts straight to your email box, for free. Delivery powered by Google Feedburner.
Did you find this tutorial helpful? Then please be generous and support Xmodulo!