Most of the system commands can be run as a root user or a user with sudo privileges. It’s not a good idea to always login as a root user. The secure way is to disable root login after creating a new user and providing him sudo privileges.
In this tutorial, we will learn how to add a user to sudoers list in Linux. The commands are generic to Linux and they will work on every distributions, such as Ubuntu, CentOS, Debian, etc.
Steps to Add a User to sudoers list in Linux
1. Create a User
Let’s first create a user for our tutorial. This is an optional step. If you already have a user to add to the sudoers list, then you can skip this step.
We will use adduser command to create a user. You should be logged in as root or a user with sudo privileges to run these commands. If you are a sudo user, then add “sudo” before all the commands.
root@localhost:~# adduser journaldev Adding user `journaldev' ... Adding new group `journaldev' (1003) ... Adding new user `journaldev' (1002) with group `journaldev' ... Creating home directory `/home/journaldev' ... Copying files from `/etc/skel' ... Enter new UNIX password: Retype new UNIX password: passwd: password updated successfully Changing the user information for journaldev Enter the new value, or press ENTER for the default Full Name : Room Number : Work Phone : Home Phone : Other : Is the information correct? [Y/n] Y root@localhost:~#
The most important point is to remember the password for the new user.
Let’s run the
groups journaldev command to check the user group details.
root@localhost:~# groups journaldev journaldev : journaldev
2. Add user to the sudo group
We can add the user to the sudo group using the following command.
root@localhost:~# usermod -aG sudo journaldev root@localhost:~#
Let’s again check the user groups to confirm that he has been added to the sudoers list.
root@localhost:~# groups journaldev journaldev : journaldev sudo root@localhost:~#
3. Validate the Sudo Access of the user
Let’s quickly validate that the user is part of the sudoers list by running some commands with “sudo” prefix.
First of all, use the su command to change the user.
root@localhost:~# su - journaldev To run a command as administrator (user "root"), use "sudo <command>". See "man sudo_root" for details. journaldev@localhost:~$
Let’s run some commands as the normal user and then as the superuser using sudo prefix.
journaldev@localhost:~$ ls -ltr /root ls: cannot open directory '/root': Permission denied journaldev@localhost:~$ journaldev@localhost:~$ sudo ls -ltr /root [sudo] password for journaldev: total 4 drwxr-xr-x 2 root root 4096 Apr 28 11:12 a.txt -rw-r--r-- 1 root root 0 Apr 28 11:12 linux.txt -rw-r--r-- 1 root root 0 Apr 28 11:21 journaldev.txt -rw-r--r-- 1 root root 0 Apr 28 11:22 lfd.txt -rw-r--r-- 1 root root 0 Apr 28 11:22 test.txt journaldev@localhost:~$
That’s it. Our user is part of the sudoers list. We can run any command as a superuser now.