How to specify a private key file in SSH

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 ssh command.

Assume that you want to access ec2-23-22-230-24.compute-1.amazonaws.com with a private key located in ~/.ssh/alice.pem:

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

$ 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 -i option.

$ 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 ~/.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 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 23.22.230.24
  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 alice@my_ec2_host

Support Xmodulo

This website is made possible by minimal ads and your gracious donation via PayPal or credit card

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.

Xmodulo © 2021 ‒ AboutWrite for UsFeed ‒ Powered by DigitalOcean