Couple days ago I wrote an article about having trouble authenticating when trying to login to remote server with key authentication and steps to solves the problem. The article is here:
SSH Authentication Refused Bad Ownership or Modes for Directory
So I thought then I should write an article about how to ssh remote linux server with key authentication.
In this example, I prepare two demo server and the information is below
The main idea of key authentication is
- generate private/public key on the source server, in our case is
- copy the generated public key to destination server, which is
Before we start, let’s take a look of the initial state first. It is crucial to know the differences between before and after.
ssh-keygen will generate files to the logged in user home directory, so let’s take a look of
Now let’s start generate the keys in
coffee with command
1 ssh-keygen -t rsa -b 4096
From the image we learn that the generated files are saved at
/home/username/.ssh/ directory and the files are
id_rsa, which is your private key, and
id_rsa.pub, which is your public key. ssh-keygen will prompt you three times, the first one is asking if you would like to specify a file to save the key rather the default value. Usually we just go with the default value so just hit enter.
The second and third prompt is asking if you would like to set a password to your private key. This is very important cause the private key is used to / can access to all servers that is setup with private key. So if anyone get hold of your private key, that person has access to all your servers. So it is very important to add passphrase to your private key for protection. If you do not wish to add passphrase, just simpely hit enter at the prompts.
ssh-keygen can generate types of key such as
For more information about the differences between each tyes, please refer here:
How to use ssh-keygen to generate a new SSH key | SSH.COM
Now let’s check out
coffee's home directory. We can see that a new hidden directory
.ssh is created with your
public keys inside.
Next we need to copy the public key, which is
tea. Many articles would teach you to
- Copy the content of the key.
- Login to
user home directoryif it does not exists.
- Create a file call
authorized_keysinside .ssh directory.
- Paste the copied content into authorized_keys.
Now all those troublesome steps can be simplified into just one command.
1 ssh-copy-id [email protected]
All you have to do is key in the password of user
tea and ssh-copy-id will do the rest for you!
Now we are all set! If everything is setup correctly, you should have the same result as the image shown below.