How to add ssh key for passwordless connection in Ubuntu

Posted by : on

Category : Infrastructure

Why you may want to read this article

Multiple times, I have configured different ubuntu machines and set up all infra for CI/CD and infra inside the servers.

The first thing I usually do is change ssh access to passwordless with public/private ssh keys from the machine. So you can connect to the server only from your machine.

This article is a step-by-step guide about how to create an ubuntu user, how to configure your ssh key on the Client (your machine), and how to configure passwordless access in your Server.

Optional: Working with files in ubuntu

You could use whatever tool in Ubuntu you want, but I prefer nano, because it is simpler than default vim.

apt install nano

To open file

nano <filename>
//inside opened file

//to save changes: 
ctrl + O

//to close opened file
ctrl + x


On the client’s machine

Go to your user directory

cd ~

Run the command to generate ssh public/private pair.


Go to ssh folder

cd ~/.ssh/

You should be able to see file.


It should have the following format ssh-rsa <key> <hostname>


On the server machine

Optional: create ssh user

Run and add some password

adduser admin



usermod -aG sudo admin

Configure ssh for the server

Instead of /home/admin you can use whatever user you have created. In this article I going to assume you have user called admin.

cd /home/admin
mkdir .ssh
cd .ssh
touch authorized_keys

Put it together

Let’s say you have user called admin. And the .ssh folder is located in /home/admin folder.

Copy the line from the Client’s ~/.ssh/ and append this line to the Server’s /home/admin/.ssh/authorized_keys


The line you are going to append is in ssh-rsa <key> <hostname> format. Append it from new line if you already have ssh keys in authorized_keys file.


sudo service ssh restart

to restrict password ssh authentication uncomment and set this in /etc/ssh/sshd_config

PasswordAuthentication no

Reload ssh

sudo service ssh restart

Then from Client you can connect to Server using ssh admin@<your-ip>

About Andrii Bui

Hi, my name is Andrii. I'm Software Engineer at Microsoft with 5 years of experience.