It's best practice to not use the root account whenever possible, instead using another local user account that has rights to elevate to root when necessary. This guide will go over how to do this, as well as disable direct root logins.
Follow the steps below to create a local user account that has administrative rights on Ubuntu 18.04 (this may also work on other distros), and then disallow direct root logins.
As you begin this guide, we assume you're currently logged in as root. If you are not, you may need to prefix your commands with sudo.
adduser username. Replace username with your username of choice.
- Follow the prompts to create a password (you won't see the password as you type it, but it's typing), enter a full name, and just hit enter past all the other questions about room number, phones, and other. Type
ywhen the prompt asks you if the information is correct. Hit
returnon your keyboard.
usermod -aG sudo usernameto add your new username to the sudo group, which gives you administrative rights on the droplet.
su usernameto log in as your new user.
cd ~to head to your new user's home directory.
mkdir .ssh && cd .ssh && touch authorized_keysto create the file where you will add your public SSH key to this user, which will allow you to log in.
nano authorized_keysto open the authorized_keys file in the nano text editor. Copy your public SSH key to your keyboard and then right click anywhere in the text editor to paste it. Remove any line breaks at the end. Hit Ctrl/Cmd+X and then type
returnon your keyboard to save the file.
- Now run
sudo sed -i 's/PermitRootLogin yes/PermitRootLogin no/g' /etc/ssh/sshd_configto disallow remote root logins.
- Finally, run
sudo systemctl restart sshd.serviceto restart the SSH service and apply your changes.
- Test your changes by opening a new terminal while leaving the existing one open and attempting to log in using the new username you just created. Once you've verified everything works, you can close out both sessions.
You've now disallowed remote root logins and created a local user account that you can use in the future to execute commands on your droplet. Note that if you want to do anything that requires elevation, you'll need to type
sudo before the command (and your password after you hit Enter/return, depending on your configuration).