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 with private key located in ~/.ssh/alice.pem.

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

$ vi ~/.ssh/config
  IdentityFile ~/.ssh/alice.pem

Then you can ssh without explicitly specifying your private key with -i option.

$ ssh

Note that when you ssh, the hostname (e.g., 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 is the IP address of, and "my_ec2_host" is in /etc/hosts. Then these alternative names must be declared in ~/.ssh/config as follows.

  IdentityFile ~/.ssh/alice.pem

  IdentityFile ~/.ssh/alice.pem

Host my_ec2_host
  IdentityFile ~/.ssh/alice.pem

Then, all the following will work.

$ ssh
$ ssh alice@
$ 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 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 *