WSL SSH key and password less login

For this experiment, we are using a WSL Ubuntu instance( codetryout-laptop ) and Ubuntu VM username codetryout.

Step #1. Creating a public and private key (ssh key pair)

This step is required only one time. If you have already done this before, jump to step 2.

Run the command ssh-keygen and follow the steps. Given below an example with default values.

codetryout@codetryout-laptop:~$ ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/home/codetryout/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/codetryout/.ssh/id_rsa
Your public key has been saved in /home/codetryout/.ssh/id_rsa.pub
The key fingerprint is:
SHA256:VsO/A25z8Ifeoc1+Dpx7DXsP4AkYGaB2aIJDWfV6Mag codetryout@codetryout-laptop
The keys randomart image is:
+---[RSA 3072]----+
| .o......        |
|.o   oo  +       |
|o . =..+o +      |
| . +... o+ o     |
|   E . .S + o    |
|      .. . * *.. |
|          + O Bo.|
|         . + B.==|
|            o.*=+|
+----[SHA256]-----+
codetryout@codetryout-laptop:~$

A new keypair has been generated!

codetryout@codetryout-laptop:~$ ls -l .ssh/
total 13
-rw------- 1 codetryout codetryout 2602 Xxx 10 16:39 id_rsa
-rw-r--r-- 1 codetryout codetryout  568 Xxx 10 16:39 id_rsa.pub
-rw-r--r-- 1 codetryout codetryout  222 Xxx 10 16:39 known_hosts
...

Step #2. Exporting the SSH key to a remote server

Use ssh-copy-id command to copy the public key to a remote server, as shown below.

# Format:
# ssh-copy-id USERNAME@REMOTE_SERVER
#
codetryout@codetryout-laptop:~$ ssh-copy-id ubuntu@codetryout
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/home/codetryout/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
ubuntu@codetryout's password:

Number of key(s) added: 1

Now try logging into the machine, with: ssh ubuntu@codetryout
and check to make sure that only the key(s) you wanted were added.

codetryout@codetryout-laptop:~$ ssh ubuntu@codetryout
Welcome to Ubuntu 20.04.2 LTS (GNU/Linux 5.11.0-25-generic x86_64)
ubuntu@codetryout:~$

Step #3. SSH Password-less login using the key.

Next time on wards, the remote server will not prompt for password.

codetryout@H-ZENBOOK:~$ ssh ubuntu@codetryout
Welcome to Ubuntu 20.04.2 LTS (GNU/Linux 5.11.0-25-generic x86_64)

Your Hardware Enablement Stack (HWE) is supported until April 2025.
Last login: XXX Xx 16:48:36 XXXX from x.x.x.x
ubuntu@codetryout:~$

Notes:

The remote server must support ssh-key authentication method, and you should have the credential to copy the key.

With this, we have covered the topic, how to configure password less login. Step-by-step instructions from a WSL client to remote server.