Giving sudo to a user is frequently occurring activity on Linux. Here are some scenarios and best practices for providing sudo to users on Linux. We’ll use use Ubuntu Linux for the purpose of this tutorial.
Location of sudoers file and sudoers.d directory
Default sudoers file is located at /etc/sudoers
and the directory for including other files is /etc/sudoers.d/
There is an include directive in /etc/sudoers
as shown below:
#includedir /etc/sudoers.d
To list existing sudoers we can run
$ sudo cat /etc/sudoers $ sudo ls /etc/sudoers.d/ $ sudo cat /etc/sudoers.d/user1 ...
For better management (and automation) it is better to create a sudoer file for each user inside /etc/sudoers.d/
.
Use visudo for editing sudoers file
It is better to use visudo to edit a sudoers file. This command checks the syntax of sudoer file before saving. This avoid accidental saving of a wrong syntax file. Saving a wrong syntax file can create problem and sudo command may stop working for users having sudo access. This may cause problem if root login is disabled on that Linux machine. Here is how you can use visudo.
// Edit default /etc/sudoers file $ sudo visudo //or edit specific file $ sudo visudo -f /etc/sudoers.d/user1
visudo example with syntax error
Run sudo visudo -f /etc/sudoers.d/user1
add the following lines (syntax errors)
(wrong syntax
When you try to save this file, you will get the following error message. You will have a choice to either re-edit the file or exit. Never save wrong syntax file.
Giving sudo to user with full access and no password
To give sudo (with full access with no password prompt) to user1 add run:
$ visudo /etc/sudoers.d/user1
And add the following line to it
gopj ALL=(ALL) NOPASSWD: ALL
Note that with this approach, user will never be asked to enter password when using sudo.
Validate if user has sudo
To validate if user has sudo run run command (say pwd) as that user as sudo.
$ sudo -i -u user1 sudo pwd /home/user1