Replace the root user on ubuntu


When booting up an Ubuntu server, one of the first things to do is to create a new user and disallow root user login. This is for security reasons, since every linux server has a root account by default, it's easy for malucious users to force into the server.

Create User

Let's say we now just created an Ubuntu server, and logged in as the root user. Then we can start creating the user by running:

sudo adduser adler

It will ask you to create a user with basic informations including a password.

Add User to sudo group

In order to give this user permission as sudoer, we'll add this user to sudo user group.

usermod -aG sudo adler

Changing Password

If at any point we want to change the password, run the command:

# as root
sudo passwd adler

# as adler
passwd

we'll be able to change it.

Copy SSH Key(s)

Then we need to be able to log in as this user using SSH key. We'll copy the key(s) from root user.

mkdir /home/adler/.ssh
cp /root/.ssh/authorized_keys /home/adler/.ssh/

Then we'll change the attributes of this directory to make it accessible.

sudo chmod 0700 /home/adler/.ssh/
sudo chown -R adler:adler /home/adler/.ssh/

Disabling root login

Make sure we can log in as our new user by logging out and logging in as:

ssh adler@example.com

Change the example.com to your domain or IP.

Try some sudo commands to make sure it works:

sudo vi

You should be able to run the editor successfully after typing the password.

After confirmed, lt's block the root login to improve security. Run:

sudo vi /etc/ssh/sshd_config

(or open it with your favourite editor.) Find the line:

PermitRootLogin yes

and change that to no. If that line does not exist, add it to the file.

After that, run:

sudo service ssh restart

And it should be working. Log out and log in again as root should be blocked.

Delete User

In case we want to delete the user, run:

sudo userdel -r adler

Reference