How to specify a private key file in ssh

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.

$ ssh -i ~/.ssh/alice.pem alice@ec2-23-22-230-24.compute-1.amazonaws.com

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.

$ vi ~/.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.

$ ssh alice@ec2-23-22-230-24.compute-1.amazonaws.com

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 23.22.230.24 is the IP address of ec2-23-22-230-24.compute-1.amazonaws.com, and "my_ec2_host 23.22.230.24" 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 23.22.230.24
  IdentityFile ~/.ssh/alice.pem

Host my_ec2_host
  IdentityFile ~/.ssh/alice.pem

Then, all the following will work.

$ ssh alice@ec2-23-22-230-24.compute-1.amazonaws.com
$ ssh alice@23.22.230.24
$ 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.


Support Xmodulo

Did you find this tutorial helpful? Then please be generous and support Xmodulo!

The following two tabs change content below.
Dan Nanni is the founder and also a regular contributor of Xmodulo.com. He is a Linux/FOSS enthusiast who loves to get his hands dirty with his Linux box. He likes to procrastinate when he is supposed to be busy and productive. When he is otherwise free, he likes to watch movies and shop for the coolest gadgets.

Leave a comment

Your email address will not be published. Required fields are marked *