Google Cloud AWS

How to Setup SSH Keys on Ubuntu 20.04

Disclosure: This post may contain affiliate links, which means we may receive a commission if you click a link and purchase something that we recommended.

Pinterest LinkedIn Tumblr

SSH keys provide a secure way for logging to a server with private and public key based authentications.

In this guide you are going to learn the following ways to secure your server.

  1. Create new user with sudo privileges
  2. Disable password based auth
  3. Generate SSH Keys
  4. Configure SSH key for the user
  5. Disable password prompt while using sudo

Step 1: Create New User

Create a new user with password disabled using the following command.

sudo adduser username --disabled-password

Follow the prompts and confirm with Y, which creates the user with the user’s home directory in /home/username.

Grant sudo access to new user

Add the new user to the sudo group so the user will have admin privileges to run commands.

sudo usermod -aG sudo username

Now you have a new user with sudo rights and password disabled.

Step 2: Disable Password Authentication for User

Edit the /etc/ssh/sshd_config file to configure authentication.

sudo nano /etc/ssh/sshd_config

Add the following to the last.

Match User username
    PasswordAuthentication no

Save the file and restart SSH.

sudo systemctl restart ssh

Now the user cannot login using password.

Step 3: Generate SSH Key

Login as the user you have created above.

sudo su username

Create new .ssh directory to hold the ssh keys and navigate into it.

Don’t use sudo inside here.

mkdir .ssh
cd .ssh

Create SSH Keys.

ssh-keygen -m PEM -t rsa -b 4096 -C "your_email"

Here I have used to PEM format to generate RSA based key. If the -m PEM is removed it might generate OpenSSH key.

When prompted provide the name for the key.

Skip passphrase and complete the setup.

Now you should have 2 files inside your .ssh directory.

The is your public key and filename is your private key.

Step 4: Configure SSH key for SSH access.

To allow SSH connection you need to add the public key to the authorized_keys file.

cat >> authorized_keys

This command will create a file named authorized_keys and add the content of public key to it.

Copy the content of private key, you can make authentication to the server using this.

cat filename

This command outputs the content of your private key. Save it for auth.

Step 5: Disable Password prompt while using sudo

By default when you run sudo based commands with other user the system prompts to enter the password for the user.

As we don’t use password we need to disable it.

Exit the user shell and get back to your root shell.

Execute the command to enter visudo.

sudo visudo

Add the following to the last.


Save the file and exit.

That’s it. Now you have a user who can login only using SSH keys.

Write A Comment

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.