Chapter 3 · 3.1
Your own user with sudo
After installation, you log in as root. Root can do anything, including accidentally breaking everything. So work with your own user and only use sudo when you need to. In the examples, this user is called anna.
Creating the user
Log in as root and type:
root@web1:~# adduser anna
root@web1:~# usermod -aG sudo anna
adduser asks for a password and a few details you can leave blank. You'll need this password for sudo, so choose a strong one and store it in your password manager. With usermod -aG sudo you add anna to the sudo group, so she can run administrator commands.
On AlmaLinux and Rocky Linux you use adduser anna, passwd anna and usermod -aG wheel anna: there the group is called wheel.
Passing on your key
Copy root's keys to anna, with the correct owner:
root@web1:~# mkdir -p /home/anna/.ssh
root@web1:~# cp /root/.ssh/authorized_keys /home/anna/.ssh/
root@web1:~# chown -R anna:anna /home/anna/.ssh
root@web1:~# chmod 700 /home/anna/.ssh
root@web1:~# chmod 600 /home/anna/.ssh/authorized_keys
Testing in a second window
Keep your root session open. Open a new terminal window and log in as anna:
ssh anna@203.0.113.10
anna@web1:~$ sudo whoami
[sudo] password for anna:
root
If you see root, sudo works. From now on, you work as anna and put sudo in front of commands that need administrator rights.
Good habits
- Only use
sudo -iif you really need to run a series of commands as root, and finish withexitafterwards. - Don't give sudo
NOPASSWD: then anyone who has your session or key can become root without a password. - Is someone else working on the server too? Give them their own user with their own key. Never share an account.
