How to control sudo access on linux
Overview
sudo stands for superuser do. It allows authorized users to execute command as an another user. Another user can be regular user or superuser. However, most of the time we use it to execute command with elevated privileges.
sudo command works in conjunction with security policies, default security policy is sudoers and it is configurable via /etc/sudoers file. Its security policies are highly extendable. One can develop and distribute their own policies as plugins.
How it’s different than su
In GNU/Linux there are two ways to run command with elevated privileges:
- Using su command
- Using sudo command
su stands for switch user. Using su, we can switch to root user and execute command. But there are few drawbacks with this approach.
- We need to share root password with another user.
- We cannot give controlled access as root user is superuser
- We cannot audit what user is doing.
sudo addresses these problems in unique way.
- First of all, we don’t need to compromise root user password. Regular user uses its own password to execute command with elevated privileges.
- We can control access of sudo user meaning we can restrict user to execute only certain commands.
- In addition to this all activities of sudo user are logged hence we can always audit what actions were done. On Debian based GNU/Linux all activities are logged in /var/log/auth.log file.
Later sections of this tutorial sheds light on these points.
Hands on with sudo
Now, we have fair understanding about sudo. Let us get our hands dirty with practical. For demonstration, I am using Ubuntu. However, behavior with another distribution should be identical.
Allow sudo access
Let us add regular user as a sudo user. In my case user’s name is linuxtechi
1) Edit /etc/sudoers file as follows:
2) Add below line to allow sudo access to user linuxtechi:
In above command:
- linuxtechi indicates user name
- First ALL instructs to permit sudo access from any terminal/machine
- Second (ALL) instructs sudo command to be allowed to execute as any user
- Third ALL indicates all command can be executed as root
Execute command with elevated privileges
To execute command with elevated privileges, just prepend sudo word to command as follows:
When you execute this command, it will ask linuxtechi’s password and not root user password.
Execute command as an another user
In addition to this we can use sudo to execute command as another user. For instance, in below command, user linuxtechi executes command as a devesh user:
Built in command behavior
One of the limitation of sudo is – Shell’s built in command doesn’t work with it. For instance, history is built in command, if you try to execute this command with sudo then command not found error will be reported as follows:
Access root shell
To overcome above problem, we can get access to root shell and execute any command from there including Shell’s built in.
To access root shell, execute below command:
After executing this command – you will observe that prompt sign changes to pound (#) character.
Recipes
In this section we’ll discuss some useful recipes which will help you to improve productivity. Most of the commands can be used to complete day-to-day task.
Execute previous command as a sudo user
Let us suppose you want to execute previous command with elevated privileges, then below trick will be useful:
Above command will execute 4th command from history with elevated privileges.
If you want to execute the previous command with root privileges using sudo command, then use following command,
sudo command with Vim
Many times we edit system’s configuration files and while saving we realize that we need root access to do this. Because this we may lose our changes. There is no need to get panic, we can use below command in Vim to rescue from this situation:
In above command:
- Colon (:) indicates we are in Vim’s ex mode
- Exclamation (!) mark indicates that we are running shell command
- sudo and tee are the shell commands
- Percentage (%) sign indicates all lines from current line
Execute multiple commands using sudo
So far we have executed only single command with sudo but we can execute multiple commands with it. Just separate commands using semicolon (;) as follows:
In above command:
- Double hyphen (–) stops processing of command line switches
- bash indicates shell name to be used for execution
- Commands to be executed are followed by –c option
Run sudo command without password
When sudo command is executed first time then it will prompt for password and by default password will be cached for next 15 minutes. However, we can override this behavior and disable password authentication using NOPASSWD keyword as follows:
Restrict user to execute certain commands
To provide controlled access we can restrict sudo user to execute only certain commands. For instance, below line allows execution of echo and ls commands only
Append line or text string to a file using sudo command
There are some scenarios where we to append a few lines to a existing file with local user who has sudo rights,
$ echo ‘text-string’ | sudo tee -a
Example is shown below :
Alternate way to append lines or text to existing file using sudo command,
Insights about sudo
Let us dig more about sudo command to get insights about it.
If you observe file permissions carefully, setuid bit is enabled on sudo. When any user runs this binary it will run with the privileges of the user that owns the file. In this case it is root user.
To demonstrate this, we can use id command with it as follows:
When we execute id command without sudo then id of user linuxtechi will be displayed.
But if we execute id command with sudo then id of root user will be displayed.
Conclusion
Takeaway from this article is – sudo provides more controlled access to regular users. Using these techniques multiple users can interact with GNU/Linux in secure manner.
Sudo user in Linux will have permissions similar to a root user. With full sudo privileges, a user will be able to perform any operations on the Linux system.
It is very important to categorize a user as a sudo user based on the use case.
In this guide, we will look in to the following.
- Create a new Linux user
- Adding full sudo privileges to a user
- Adding sudo privileges for specific command execution.
Create a new Linux user
Step 1: Login to your server as root.
Step 2: Create a user using useradd command. Replace username with your custom user.
Step 3: Set a password for the user.
You will be prompted for updating the new password. Enter the required password.
Add sudo Privileges to a User
Now lets make our new user or an exiting user a sudo user.
Step1: Add the user to wheel group.
Note: If a user is part of wheel group, he can run any command as a super user.
Step 2: Execute visudo command to open /etc/sudoers file.
Step 3: Make sure the following line is uncommented in the file.
By default, even if a user is part of wheel group, you need to provide the password every time you run a command as sudo. If you need password less sudo access, you need uncomment the following where it has NOPASSWD and save the file using ESC + w + q + !
Step 4: Now lets test the sudo user by logging in as the user.
Now, try running sudo commands. It should work based on your password preferences (with or without password) you set for wheel group.
Adding sudo privileges for specific command execution.
There are scenarios where you might want only specific commands to be run a sudo privileges for a specific user. Lets see how we can achieve it.
You can group the set of commands to be run under Cmnd_Alias
For example, if you open the /etc/sudoers file, you can find the following aliases.
Lets say, you want a user to have only permissions to run commands under the SERVICES alias, you need to have the following entry in the /etc/sudoers file
Note: You can have custom commands in aliases the you create under Cmnd_Alias
Among the different concepts of an operating system, the most crucial one is access control, which specifies the level of access that is granted to each user of that operating system. The access control policies ensure that no user is allowed to perform those activities for which he has not been granted any privileges. The two most common types of users in any operating system are the root user (has administrative level privileges) and the guest user (only has a limited set of privileges).
At times, even a guest user needs to perform some tasks that require administrative privileges. Fortunately, Linux provides us with a way of doing this, i.e., by making use of the “sudo” keyword before a command. It is such a magical keyword that whichever command is followed by this keyword is allowed to run with the root privileges rather than its own limited privileges. Sudo stands for Super User DO. For today’s discussion, our aim is to explain to you the usage of the “sudo” command in Linux.
Note: We have used Linux Mint 20 for explaining the method of using the “sudo” command.
The method of using the “sudo” command in Linux Mint 20 will be demonstrated by the following three example scenarios:
Scenario # 1: Updating your System with the Sudo Command
Whenever you want to install any new program, application, package, or command in your Linux system, you are always advised to update your system’s cache before it. It is so because, at times, some existing packages might be unpatched, which can cause trouble for you while installing anything new on your system. You can execute the “update” command with the root user privileges. Therefore, for updating your system with the sudo command, you will have to do the steps mentioned below:
In the first step, launch the terminal in any Linux distribution (I am using Linux Mint 20); it can be done by clicking on the terminal icon present on the. You can visualize the Linux Mint 20 terminal in the following image:
Once you have launched the terminal, the next thing you need to do is to run the “update” command while making use of the “sudo” keyword before it as shown below:
When you hit the Enter key, the “update” command will take a few seconds to complete its execution, depending upon the total number of packages to be updated. The more the broken or outdated packages or dependencies are, the more time it will consume to execute the “update” command. However, once its execution finishes, your terminal will manifest the following output on it:
Scenario # 2: Upgrading your System with the Sudo Command
Usually, after a system update, you are required to upgrade those packages, too, whose upgraded versions are available on the Internet. This process takes a little longer than running the simple “update” command because, after all, you are installing all the newer versions of the packages whose upgrades are available. Moreover, these upgrades also require additional space on your system. Again, for upgrading the packages on your system, you need to run the “upgrade” command with the “sudo” privileges, which can be done as follows:
In your Linux Mint 20 terminal, you are supposed to execute the following command:
Once you press the Enter key to run this command, you will be asked for confirmation regarding whether you actually want to upgrade your packages or not. This is done because Linux considers it mandatory for asking the user before installing any such package that occupies an additional space on his system as well as requires a sufficient amount of time. If you are sure to carry on with this process, you can simply convey this to your OS by typing in “Y” in your terminal and then pressing the Enter key as highlighted in the image shown below:
It will take some minutes for the “upgrade” command to complete its execution, which again depends on the exact number of packages that are to be upgraded. However, once all the packages have been upgraded, your terminal will display the following output on it:
Scenario # 3: Creating a Text File with the Sudo Command
For accessing most of the text editors in the Linux operating system, you require root user privileges. Similarly, for creating a text file with the nano editor, you have to do it while making use of the “sudo” keyword, and the whole process is explained in the steps mentioned below:
In the first step, you have to execute the following command:
You can replace “MyFile.txt” with any name of your choice to your text file instead of naming it MyFile.txt. As in this case, we have named our text file as Sudo.txt.
Once you run this command, it will not only create a new empty text file with the specified name in your Home directory, but it will also open that file with the nano editor from where you can add any content of your choice to this file as shown in the following image:
After making all these changes, you need to save your file and exit from the nano editor simply by pressing Ctrl+ X. You can also verify if a text file has actually been created in your Home directory by running the “sudo” command or not simply by going to your Home directory. Here, you will be able to find your newly created text file, as shown in the image below:
Conclusion
In this article, we tried to give you a brief overview of the usage of the “sudo” command in Linux Mint 20. These are just some of the example scenarios in which you can effectively make use of this command. However, this keyword can be used with a large number of other commands as well as on the other flavors of the Linux operating system.
About the author
Aqsa Yasin
I am a self-motivated information technology professional with a passion for writing. I am a technical writer and love to write for all Linux flavors and Windows.
PHP Code
- Home
- Security
- How to Use the sudo Command in Linux
Introduction
Sudo stands for SuperUser DO and is used to access restricted files and operations. By default, Linux restricts access to certain parts of the system preventing sensitive files from being compromised.
The sudo command temporarily elevates privileges allowing users to complete sensitive tasks without logging in as the root user. In this tutorial, learn how to use the sudo command in Linux with examples.
Prerequisites
- A system running Linux
- Access to a command line/terminal window (Activities > Search > Terminal)
- A user account with sudo or root privileges
How to use the sudo Command
sudo was developed as a way to temporarily grant a user administrative rights. To make it work, use sudo before a restricted command. The system will prompt for your password. Once provided, the system runs the command.
Syntax
To start using sudo , use the following syntax:
When the sudo command is used, a timestamp is entered in the system logs. The user can run commands with elevated privileges for a short time (default 15 minutes). If a non-sudo user tries to use the sudo command, it is logged as a security event.
Options
sudo can be used with additional options:
- -h – help; displays syntax and command options
- -V – version; displays the current version of the sudo application
- -v – validate; refresh the time limit on sudo without running a command
- -l – list; lists the user’s privileges, or checks a specific command
- -k – kill; end the current sudo privileges
Additional options can be found under the -h option.
Note: Staying logged in as an administrator compromises security. In the past, admins would use su (substitute user) to temporarily switch to an administrator account. However, the su command requires a second user account and password, which isn’t always feasible.
Granting sudo Privileges
For most modern Linux distributions, a user must be in the sudo, sudoers, or wheel group to use the sudo command. By default, a single-user system grants sudo privileges to its user. A system or server with multiple user accounts may exclude some users from sudo privileges.
We recommend to only grant privileges that are absolutely necessary for the user to perform daily tasks.
The following sections explain how to add a user to the sudoers group.
RedHat and CentOS
In Redhat/CentOS, the wheel group controls sudo users. Add a user to the wheel group with the following command:
Replace [username] with an actual username. You may need to log in as an administrator or use the su command.
Debian and Ubuntu
In Debian/Ubuntu, the sudo group controls sudo users. Add a user to the sudo group with the following command:
Replace [username] with an actual username. You may need to log in as an administrator or use the su command.
Using visudo and the sudoers Group
In some modern versions of Linux, users are added to the sudoers file to grant privileges. This is done using the visudo command.
1. Use the visudo command to edit the configuration file:
2. This will open /etc/sudoers for editing. To add a user and grant full sudo privileges, add the following line:
3. Save and exit the file.
Here’s a breakdown of the granted sudo privileges:
Note: It’s easier to simply add a user to the sudo or wheel group to grant sudo privileges. If you need to edit the configuration file, only do so using visudo . The visudo application prevents glitches, bugs, and misconfigurations that could break your operating system.
Linux depends upon administrative user permission. Without the elevated permission of root, many commands could not be run. For distributions, such as Red Hat, gaining root permissions means changing to the root user with the command su . Other distributions, such as Ubuntu Linux, opt for a different route. That route is sudo. By taking advantage of the sudo system, an administrator gains far more control over who can do what on a system. An added benefit of using the sudo command is that all sudo incidents are logged (Red Hat-based systems log to /var/log/secure whereas Debian-based systems log to /var/log/auth.log ).
Say, for example, you want to give certain users permission to use a certain command, without having to enter their sudo password. With sudo you can do that. You can also join users into groups, to make controlling who can do what much easier.
Now that I have your interest piqued, how do you manage/configure sudo on your Linux machine? The answer is simple… sudoers . In the file /etc/sudoers , you’ll find everything you need to wrestle control over sudo.
A word of caution
Taking on the /etc/sudoers file must be done with care. You should never open that file with a standard text editor (such as nano or vi). Instead, use the built-in visudo tool. This tool will parse the file to see if there are any problems. Once you’ve made changes to the file, you can even run the command sudo visudo -c to run a second automatic parse of the file. Should visudo find issues, fix them immediately before closing your terminal (otherwise, you can wind up locked out of all command that require sudo (trust me, I did this once…it’s no fun)
It is also important to understand:
The sudo binary is setuid root, which means that when any user runs a command through sudo, they are instantly granted root permissions. Because of this, you must take extra precaution when working with the /etc/sudoers file; otherwise, you could find your system at serious risk.
The sudo command reads the sudoers file in top-to-bottom order. In other words, the last line in /etc/sudoers will overwrite previous conflicts with the setup. Because of this, you should always enter your new lines at the bottom of each /etc/sudoers section.
The sudo command includes a number of defaults that can be set within /etc/sudoers . To find a listing of these defaults, issue the command sudo -L.
Now that you clearly understand the importance of editing /etc/sudoers with visudo , let’s take a look and see what you can do.
The file
There are a few sections of the sudoers file you need to know about:
Defaults: These are the default variables for sudo (remember, sudo -L is your friend)
Alias: You can create aliases for host, user, and commands
User privilege: This is where you specify user privilege
Groups: This is where you define groups
You may be surprised to find out the default sudoers file is only 31 lines long (at least in Ubuntu 16.10). It’s not overly complicated, nor is it much of a challenge to understand. However, understanding the breakdown of user privilege lines is very important. The structure of these lines is:
The breakdown of this line is:
user : The account for which the privilege will be associated
host : The system from which the account is able to run these sudo commands ( sudoers can be shared across systems)
accounts : The other accounts on the machine for which the user running sudo can act
commands : The commands the user can run as sudo
If you issue the command sudo visudo, the default /etc/sudoers file will open. In that file, there will only be one line under user privilege. That line is:
According to our breakdown, that command means the root user from all hosts from any account can run all commands .
Aliases
Before we get into adding user permission entries to sudoers , it is important to understand how aliases work. Sudoers aliases come in the form of:
User_Alias — specifies a group of users by username
Runas_Alias — specifies a group of users by UID
Host_Alias — specifies a list of hostnames
Cmnd_Alias — specifies a list of commands and directories
A typical alias looks like:
The above alias would include bethany, jamal, morgan, and josh with the alias named USERS . You can also include groups with aliases, such as:
The percent sign indicates to sudo that admin is a system group. To include netgroups, you would prefix the group name with the + symbol. You can also exclude users from an alias by prefixing their name with the ! symbol. Say, for instance, you want to create an alias for restricted users, based on previous aliases. Say users bethany, jamal, morgan, josh, and jonathan are all members of the ADMINS alias, and you want to create an alias for WEBMASTER that does not include the user jonathan. Instead of entering every user, to be included, you could add the admin group and then exclude jonathan like so:
That’s how aliases work.
Adding entries
Remember, to edit the /etc/sudoers file, we do so with the command sudo visudo .
Our example will be to enable certain users to shutdown the system without having to enter a password. To do this, we will first create a User_Alias for ADMINS. Under the User alias section, add the line:
Where usernames is the list of names to be included with the alias.
Next we create a Cmnd_Alias for the shutdown commands. Under the Cmnd alias section, enter this line:
Finally, under the User privilege section (below the default entry of ALL=(ALL:ALL) ALL ), enter the following:
Save the file and then (for added assurance that everything is okay), issue the command sudo visudo -c . You should see the same output as shown in Figure 1 .
Figure 1: Everything is okay and ready to test.
To test the new sudoers entry, you’ll need to logout and log back in. Once you’ve done that, open up a terminal window and issue the command shutdown -h now as one of the users listed in the user alias ADMINS. Your system should shut down without prompting for a password.
An eye on security
Obviously, with regards to security, this isn’t the greatest example. However, it does perfectly illustrate how powerful sudoers can be. You will certainly want to tailor your sudoers file to meet your admin needs on every level. Most likely, you won’t create an entry that would allow just any user to shutdown the system without entering a password. However, with a keen eye toward security, you can make sudoers work well for you.
Advance your career in system administration! Check out the Essentials of System Administration course from The Linux Foundation.
Objective
Operating System and Software Versions
- Operating System: – All Linux distributions
Requirements
- Root permissions
Difficulty
Conventions
- # – requires given linux commands to be executed with root privileges either directly as a root user or by use of sudo command
- $ – requires given linux commands to be executed as a regular non-privileged user
Introduction
Restrict root login
What we see there it’s just a list of all the terminals from which direct access as the root user is allowed. Let’s focus on the tty devices for now. Open the file with a text editor and comment the tty1 entry: Save and exit the text editor. Now, if we switch to the first tty by pressing CTRL + alt + 1 or by running chvt 1 , and try to login as root, we will have the following result:
As expected, the system denied us access as root from the specified tty. To gain root privileges and accomplish administrative tasks, we must then login as a normal user and then use sudo or su (or login from another tty if allowed).
Be aware that this will not affect the ability to login as root when using ssh. To avoid that specific behaviour you should configure the ssh server, modifying the /etc/ssh/sshd_config file, and set the PermitRootLogin directive to no
Setup access rules in /etc/security/access.conf
If the /etc/securetty file allows us to specify from which terminal it is possible to login directly as root, setting up access rules in the /etc/security/access.conf file, we can allow or deny access to specific users or groups from specific origins.
Insert the pam_access.so module
The rules syntax
To define a rule in the access.conf file, we must respect a very simple and clear syntax. A rule is composed of three sections, separated by a colon: The first part of the rule specifies the permissions, and consists of a – or + sign: the former creates what we can call a ‘deny’ rule, while the latter specifies a rule where access permissions are granted.
In the second part we provide the subjects of the rule. The section consists of a list of groups or login names. To avoid conflicts between users and groups which can be named in the same way, the group entries can be specified in brackets, but only if the nodefgroup option is set in the /etc/pam.d/login file we modified above, at the end of the line we added.
The third part of the rule specifies the source from which the access is either allowed or denied, being it: one or more ttys , host names, host addresses, or domains.
Keywords
The rule syntax let us even use some powerful keywords. First of all we have ALL . This keyword will always match: for example, when used in the second section, it will match all possible users or groups, or when used in the third, all possible sources.
The NONE keyword has the exact opposite effect of ALL , and LOCAL , which has sense only in the origins section of the rule, will match every string which does not contain a ‘.’. Finally a very powerful keyword is EXCEPT which allows us to specify exceptions to a set rule.
Some examples
The file provides some useful examples, let’s look at some of them. First of ALL we have the following: This line, would let us obtain the opposite result we have obtained before by modifying the /etc/securetty file: first of all we have the – sign, which means it is a deny rule. In the next section, separated by a colon, we have ALL EXCEPT root , which specifies that the rule must be applied to all users except root , and in the third section, we see that the specified rule is valid only when someone tries to access from tty1 .
Another example, this time with multiple usernames: The rule forbids access to the wsbscaro, wsbsecr, wsbspac, wsbsym, wscosor and wstaiwde users from all sources (see the ALL keyword in action)
Something more complex. This time the rule denies access to all users who are not member of the wheel group on local logins:
Finally an example which specifies a rule for a remote login: As we now should understand, this rule allows root to access the system only from the specified ip addresses.
The sudo command gives some admin privileges to non-admin users
- Tweet
- Share
Certain Linux applications require elevated privileges to run. Use the su command to switch to the superuser (root), or you can use the sudo command instead.
How It Works
Although they work differently, the sudo command is analogous to the confirmation prompt you sometimes see in Windows or macOS. When asked in those operating systems if you want to continue performing that specific action, you’re met with a button to confirm that you want to run the action with elevated privileges, and at times you might even have to enter an admin’s password.
Linux uses the sudo command as a wall between normal tasks and administrative ones, so that you have to confirm that you want to do whatever it is that the command will execute, and that you’re authorized to perform the task. Even more similar is the run as command in Windows; like in Linux, the run as command works from the command line to launch a file with credentials from a certain user, often an admin.
If you’re not sure if you’re using sudo or su, look at the trailing character on the command line. If it’s a pound sign (#), you’re logged in as root.
About the Sudo Command
When you put sudo in front of any command in terminal, that command runs with elevated privileges, which is why it’s the solution to privilege-related errors.
Sudo operates on a per-command basis. Features include the ability to restrict the commands a user can run on a per-host basis, copious logging of each command to provide a clear audit trail of who did what, a configurable timeout of the sudo command, and the ability to use the same configuration file on many different machines.
Sudo Command Example
A standard user without administrative privileges might enter a command in Linux to install a piece of software:
The command returns an error because a person without administrative privileges isn’t allowed to install software. However, the sudo command comes to the rescue. Instead, the correct command for this user is:
This time the software installs.
You can also configure Linux to prevent some users from using the sudo command.
The Linux super user, or root user, is a special user that has tremendous power, with the ability to access and modify all files on the operating system. This is necessary at times, but there is a potential for accidental errors to cause a great deal of destruction, so you have to be careful. (Like Spiderman says, with great power comes great responsibility.) Fot the times when the super user’s power is necessary, we’ll look at safer ways to be the super user on your Linux dedicated server.
Super User and Sudo
A really important feature of Linux is privileges. It’s part of the security, and controls which users can access, manipulate or even be aware of what files. Logged in with the user account we’ve created will allow safe usage of the operating system, but there are times when the privileges of the root, or super user are required.
There are two ways to access super user privileges. The first is with the su command.
If you enter this command, and note the hyphen, then you will be prompted for the root user’s password. Enter it correctly, and you will be logged in as the super user. You can then perform what tasks you need to, but with care! When you’ve finished, log out immediately using the exit command.
The second way to get super user privileges is to use sudo. This is a method by which a regular user can gain a temporary privilege boost. It takes a little setting up, but once done it is probably safer than the su command method.
First, log in to your server. Then, log in as root using the su command. Then, enter the following.
This will open up a text file that contains information for sudo. A little way down the file you’ll see the following text.
# User privilege specification
root ALL=(ALL) ALL
You need to add yourself to the file in order to get your privileges. To do this, you need to do a little editing. Use the arrow keys to move the cursor to this line, then press i on the keyboard. You’re now editing the file, so enter the following line:
YourUserName ALL=(ALL) ALL
Of course substitute your user name for YourUserName, then press escape, and type ZZ (capital Z twice). This will save the file, and that’s it. If you’ve done it right, you can now use sudo. To test this, log out as the root user (type exit, hit return), then try the following.
You should receive an error message telling you that permission is denied. So, try it with sudo.
Now you will be asked for a password. Enter your own password at this point (not the root password) and hey presto, you’ll be presented with a listing of the root user’s directory. So, any time that you wish to do something that requires root user privileges, remember that you can use the sudo command, saving you from logging in as the root user.
Logging out
To log out of your ssh session, and so your server, at any time, type:
If you are logged in as the super user having used the su command, remember that you may need to type this twice.
Now we know how to log in and out we want to do something constructive with the server, but before we get to the commands we should take a look at the Linux directory structure.
Like most things on Linux, the sudo command is very configurable. You can have sudo run specific commands without asking for a password, restrict specific users to only approved commands, log commands run with sudo, and more.
The sudo command’s behavior is controlled by the /etc/sudoers file on your system. This command must be edited with the visudo command, which performs syntax-checking to ensure you don’t accidentally break the file.
Specify Users With Sudo Permissions
The user account you create while installing Ubuntu is marked as an Administrator account, which means it can use sudo. Any additional user accounts you create after installation can be either Administrator or Standard user accounts – Standard user accounts don’t have sudo permissions.
You can control user account types graphically from Ubuntu’s User Accounts tool. To open it, click your user name on the panel and select User Accounts or search for User Accounts in the dash.
Make Sudo Forget Your Password
By default, sudo remembers your password for 15 minutes after you type it. This is why you only have to type your password once when executing multiple commands with sudo in quick succession. If you’re about to let someone else use your computer and you want sudo to ask for the password when it runs next, execute the following command and sudo will forget your password:
Always Ask For a Password
If you’d rather be prompted each time you use sudo – for example, if other people regularly have access to your computer — you can disable the password-remembering behavior entirely.
This setting, like other sudo settings, is contained in the /etc/sudoers file. Run the visudo command in a terminal to open the file for editing:
In spite of its name, this command defaults to the new-user-friendly nano editor instead of the traditional vi editor on Ubuntu.
Add the following line below the other Defaults lines in the file:
Press Ctrl+O to save the file, and then press Ctrl+X to close Nano. Sudo will now always prompt you for a password.
Change the Password Timeout
To set a different password timeout – either a longer one like 30 minutes or a shorter one like 5 minutes – follow the steps above but use a different value for timestamp_timeout. The number corresponds to the number of minutes sudo will remember your password for. To have sudo remember your password for 5 minutes, add the following line:
Never Ask for a Password
You can also have sudo never ask for a password – as long as you’re logged in, every command you prefix with sudo will run with root permissions. To do this, add the following line to your sudoers file, where username is your username:
You can also change the %sudo line – that is, the line that allows all users in the sudo group (also known as Administrator users) to use sudo – to have all Administrator users not require passwords:
Run Specific Commands Without a Password
You can also specify specific commands that will never require a password when run with sudo. Instead of using “ALL” after NOPASSWD above, specify the location of the commands. For example, the following line will allow your user account to run the apt-get and shutdown commands without a password.
username ALL=(ALL) NOPASSWD: /usr/bin/apt-get,/sbin/shutdown
This can be particularly useful when running specific commands with sudo in a script.
Allow a User to Run Only Specific Commands
While you can blacklist specific commands and prevent users from running them with sudo, this isn’t very effective. For example, you could specify that a user account not be able to run the shutdown command with sudo. But that user account could run the cp command with sudo, create a copy of the shutdown command, and shut down the system using the copy.
A more effective way is to whitelist specific commands. For example, you could give a Standard user account permission to use the apt-get and shutdown commands, but no more. To do so, add the following line, where standarduser is the user’s username:
The following command will tell us what commands the user can run with sudo:
Logging Sudo Access
You can log all sudo access by adding the following line. /var/log/sudo is just an example; you can use any log file location you like.
View the contents of the log file with a command like this one:
Bear in mind that, if a user has unrestricted sudo access, that user has the ability to delete or modify the contents of this file. A user could also access a root prompt with sudo and run commands that wouldn’t be logged. The logging feature is most useful when coupled with user accounts that have restricted access to a subset of system commands.
Among the different concepts of an operating system, the most crucial one is access control, which specifies the level of access that is granted to each user of that operating system. The access control policies ensure that no user is allowed to perform those activities for which he has not been granted any privileges. The two most common types of users in any operating system are the root user (has administrative level privileges) and the guest user (only has a limited set of privileges).
At times, even a guest user needs to perform some tasks that require administrative privileges. Fortunately, Linux provides us with a way of doing this, i.e., by making use of the “sudo” keyword before a command. It is such a magical keyword that whichever command is followed by this keyword is allowed to run with the root privileges rather than its own limited privileges. Sudo stands for Super User DO. For today’s discussion, our aim is to explain to you the usage of the “sudo” command in Linux.
Note: We have used Linux Mint 20 for explaining the method of using the “sudo” command.
The method of using the “sudo” command in Linux Mint 20 will be demonstrated by the following three example scenarios:
Scenario # 1: Updating your System with the Sudo Command
Whenever you want to install any new program, application, package, or command in your Linux system, you are always advised to update your system’s cache before it. It is so because, at times, some existing packages might be unpatched, which can cause trouble for you while installing anything new on your system. You can execute the “update” command with the root user privileges. Therefore, for updating your system with the sudo command, you will have to do the steps mentioned below:
In the first step, launch the terminal in any Linux distribution (I am using Linux Mint 20); it can be done by clicking on the terminal icon present on the. You can visualize the Linux Mint 20 terminal in the following image:
Once you have launched the terminal, the next thing you need to do is to run the “update” command while making use of the “sudo” keyword before it as shown below:
When you hit the Enter key, the “update” command will take a few seconds to complete its execution, depending upon the total number of packages to be updated. The more the broken or outdated packages or dependencies are, the more time it will consume to execute the “update” command. However, once its execution finishes, your terminal will manifest the following output on it:
Scenario # 2: Upgrading your System with the Sudo Command
Usually, after a system update, you are required to upgrade those packages, too, whose upgraded versions are available on the Internet. This process takes a little longer than running the simple “update” command because, after all, you are installing all the newer versions of the packages whose upgrades are available. Moreover, these upgrades also require additional space on your system. Again, for upgrading the packages on your system, you need to run the “upgrade” command with the “sudo” privileges, which can be done as follows:
In your Linux Mint 20 terminal, you are supposed to execute the following command:
Once you press the Enter key to run this command, you will be asked for confirmation regarding whether you actually want to upgrade your packages or not. This is done because Linux considers it mandatory for asking the user before installing any such package that occupies an additional space on his system as well as requires a sufficient amount of time. If you are sure to carry on with this process, you can simply convey this to your OS by typing in “Y” in your terminal and then pressing the Enter key as highlighted in the image shown below:
It will take some minutes for the “upgrade” command to complete its execution, which again depends on the exact number of packages that are to be upgraded. However, once all the packages have been upgraded, your terminal will display the following output on it:
Scenario # 3: Creating a Text File with the Sudo Command
For accessing most of the text editors in the Linux operating system, you require root user privileges. Similarly, for creating a text file with the nano editor, you have to do it while making use of the “sudo” keyword, and the whole process is explained in the steps mentioned below:
In the first step, you have to execute the following command:
You can replace “MyFile.txt” with any name of your choice to your text file instead of naming it MyFile.txt. As in this case, we have named our text file as Sudo.txt.
Once you run this command, it will not only create a new empty text file with the specified name in your Home directory, but it will also open that file with the nano editor from where you can add any content of your choice to this file as shown in the following image:
After making all these changes, you need to save your file and exit from the nano editor simply by pressing Ctrl+ X. You can also verify if a text file has actually been created in your Home directory by running the “sudo” command or not simply by going to your Home directory. Here, you will be able to find your newly created text file, as shown in the image below:
Conclusion
In this article, we tried to give you a brief overview of the usage of the “sudo” command in Linux Mint 20. These are just some of the example scenarios in which you can effectively make use of this command. However, this keyword can be used with a large number of other commands as well as on the other flavors of the Linux operating system.
About the author
Aqsa Yasin
I am a self-motivated information technology professional with a passion for writing. I am a technical writer and love to write for all Linux flavors and Windows.