Learn How to Create a sudo and restricted sudo user in Linux

A step-by-step guide to creating a new user with sudo privileges in Ubuntu, also creating a user with specific sudo permissions

Type the following command to create a new user

sudo useradd -m master -s /bin/bash

Type the following command to set a password for the new user

echo 'master:password' | sudo chpasswd

Now, we need to add the new user to the sudo group, which will give them administrative privileges. To do this, type the following command

sudo usermod -aG sudo master

Finally, test if the new user's sudo privileges are working correctly.

id master

Verify by switching to the new user and running a command as sudo

right now admin_user can run every command which requires sudo access,

How to create a user with restricted access

What if we want a user to be able to run only specific kinds of commands with sudo privileges, like adduser, apt, etc?

let's create a new user restricted and allow only to run specific commands in my case only adduser, and apt

Please note that we are not adding this user to sudo group

Before proceeding further we need to know the location of the binaries of adduser and apt commands. use which commands to get the binaries locations

Now we have created a user and assigned the password, we also have binaries of the sudo commands finally we want to give specific access to the restricted user

let's create a configuration file in /etc/sudoers.d/ called restricted

Use the following command to create the file

sudo visudo -f /etc/sudoers.d/restricted

add these lines ,

Cmnd_Alias     USERADMINISTRATOR = /usr/sbin/useradd
Cmnd_Alias     PACKAGES =  /usr/bin/apt
#ALLOWING restricted user to access to PACKAGES, USERADMINISTRATOR

from this line user restricted can only run useradd and apt commands

Test and Verify

# switch to the restricted user and run useradd , apt command
 sudo su - restricted

Notice below we have logged in as a restricted user and can run apt and adduser commands

But the catch Is here, the restricted user is unable to run systemctl commands because we were not allowed in the file at /etc/sudoers.d/restricted