Junk Food for the Brain

Open Source and Awesomesauce :)

How to Use a Different SSH Key for a Host

| Comments

There are times when you need to use just one different SSH Key for a particular host. And you’re not allowed to add your own public key into the host’s authorized_keys file due to system limitations / policies etc.

This is where the ssh config file comes in handy.

For this example, I’ll assume you want to connect to a host called db01 as the user admin. What you’ll need to do is:

Copy over the user@host’s private and public keys into your local ~/.ssh directory.

$ cd ~/.ssh
$ scp admin@db01:/home/admin/.ssh/id_rsa id_rsa_db01
$ scp admin@db01:/home/admin/.ssh/id_rsa.pub id_rsa_db01.pub

Note: I copied the keys over as different filenames, id_rsa_db01 and id_rsa_db01.pub. This is so you don’t overwrite your existing keys.

Create the ssh config file in your .ssh directory

$ touch ~/.ssh/config

Specify the user and ssh private key file to use when connecting to the host db01 in the ~/.ssh/config file. Your config file should have the following contents:

host db01
    user admin
    IdentityFile id_rsa_db01

Change the permissions of the ssh keys to read-only, and the ssh config file to be read-write only by you.

$ chmod 400 ~/.ssh/id_rsa_db01*
$ chmod 600 !/.ssh/config

The ssh config file has some pretty powerful options, and more can be read by typing man ssh_config.