- Sudo in Linux
- The sudo command gives some admin privileges to non-admin users
- How It Works
- About the Sudo Command
- Sudo Command Example
- What is sudo file in linux
- Contents
- Installation
- Usage
- Configuration
- Defaults skeleton
- View current settings
- Using visudo
- Example entries
- Sudoers default file permissions
- Tips and tricks
- Disable password prompt timeout
- Add terminal bell to the password prompt
- Passing aliases
- Disable per-terminal sudo
- Reduce the number of times you have to type a password
- Environment variables
- Root password
- Disable root login
- kdesu
- Harden with sudo example
- Configure sudo using drop-in files in /etc/sudoers.d
- Editing files
- Enable insults
- Troubleshooting
- SSH problem without TTY
- Permissive umask
- How to Use the sudo Command in Linux
- How to use the sudo Command
- Syntax
- Options
- Granting sudo Privileges
- RedHat and CentOS
- Debian and Ubuntu
- Using visudo and the sudoers Group
- Examples of sudo in Linux
- Basic Sudo Usage
- Run Command as a Different User
- Switch to Root User
- Execute Previous Commands with sudo
- Run Multiple Commands in One Line
- Add a String of Text to an Existing File
Sudo in Linux
The sudo command gives some admin privileges to non-admin users
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.
Источник
What is sudo file in linux
Sudo allows a system administrator to delegate authority to give certain users—or groups of users—the ability to run commands as root or another user while providing an audit trail of the commands and their arguments.
Sudo is an alternative to su for running commands as root. Unlike su, which launches a root shell that allows all further commands root access, sudo instead grants temporary privilege elevation to a single command. By enabling root privileges only when needed, sudo usage reduces the likelihood that a typo or a bug in an invoked command will ruin the system.
Sudo can also be used to run commands as other users; additionally, sudo logs all commands and failed access attempts for security auditing.
Contents
Installation
Usage
To begin using sudo as a non-privileged user, it must be properly configured. See #Configuration.
To use sudo, simply prefix a command and its arguments with sudo and a space:
For example, to use pacman:
See sudo(8) for more information.
Configuration
This article or section needs expansion.
Defaults skeleton
sudoers(5) § SUDOERS OPTIONS lists all the options that can be used with the Defaults command in the /etc/sudoers file.
See [1] for a list of options (parsed from the version 1.8.7 source code) in a format optimized for sudoers .
See sudoers(5) for more information, such as configuring the password timeout.
View current settings
Run sudo -ll to print out the current sudo configuration, or sudo -lU user for a specific user.
Using visudo
The configuration file for sudo is /etc/sudoers . It should always be edited with the visudo(8) command. visudo locks the sudoers file, saves edits to a temporary file, and checks it for syntax errors before copying it to /etc/sudoers .
The default editor for visudo is vi. The sudo package is compiled with —with-env-editor and honors the use of the SUDO_EDITOR , VISUAL and EDITOR variables. EDITOR is not used when VISUAL is set.
To establish nano as the visudo editor for the duration of the current shell session, export EDITOR=nano ; to use a different editor just once simply set the variable before calling visudo:
Alternatively you may edit a copy of the /etc/sudoers file and check it using visudo -c /copy/of/sudoers . This might come in handy in case you want to circumvent locking the file with visudo.
To change the editor permanently, see Environment variables#Per user. To change the editor of choice permanently system-wide only for visudo, add the following to /etc/sudoers (assuming nano is your preferred editor):
Example entries
To allow a user to gain full root privileges when they precede a command with sudo , add the following line:
To allow a user to run all commands as any user but only on the machine with hostname HOST_NAME :
To allow members of group wheel sudo access:
To disable asking for a password for user USER_NAME :
Enable explicitly defined commands only for user USER_NAME on host HOST_NAME :
Enable explicitly defined commands only for user USER_NAME on host HOST_NAME without password:
A detailed sudoers example is available at /usr/share/doc/sudo/examples/sudoers . Otherwise, see the sudoers(5) for detailed information.
Sudoers default file permissions
The owner and group for the sudoers file must both be 0. The file permissions must be set to 0440. These permissions are set by default, but if you accidentally change them, they should be changed back immediately or sudo will fail.
Tips and tricks
Disable password prompt timeout
A common annoyance is a long-running process that runs on a background terminal somewhere that runs with normal permissions and elevates only when needed. This leads to a sudo password prompt which goes unnoticed and times out, at which point the process dies and the work done is lost or, at best, cached. Common advice is to enable passwordless sudo, or extend the timeout of sudo remembering a password. Both of these have negative security implications. The prompt timeout can also be disabled and since that does not serve any reasonable security purpose it should be the solution here:
Add terminal bell to the password prompt
To draw attention to a sudo prompt in a background terminal, users can simply make it echo a bell character:
Note the ^G is a literal bell character. E.g. in vim, insert using the sequence Ctrl+v Ctrl+g , or in nano, Alt+v Ctrl+g .
Passing aliases
If you use a lot of aliases, you might have noticed that they do not carry over to the root account when using sudo. However, there is an easy way to make them work. Simply add the following to your
/.bashrc or /etc/bash.bashrc :
Disable per-terminal sudo
If you are annoyed by sudo’s defaults that require you to enter your password every time you open a new terminal, set timestamp_type to global :
Reduce the number of times you have to type a password
If you are annoyed that you have to re-enter your password every 5 minutes (default), you can change this by setting a longer value for timestamp_timeout (in minutes):
If you are using a lot of sudo commands on a row, it is more logical to refresh the timeout every time you use sudo than to increase timestamp_timeout . Refreshing the timeout can be done with sudo -v (whereas sudo -K revokes immediately).
You might want to automate this by adding the following to your .bashrc :
It is also possible to use a bash function; for more details see stackexchange.
Environment variables
If you have a lot of environment variables, or you export your proxy settings via export http_proxy=». » , when using sudo these variables do not get passed to the root account unless you run sudo with the -E option.
The recommended way of preserving environment variables is to append them to env_keep :
Root password
Users can configure sudo to ask for the root password instead of the user password by adding targetpw (target user, defaults to root) or rootpw to the Defaults line in /etc/sudoers :
To prevent exposing your root password to users, you can restrict this to a specific group:
Disable root login
Users may wish to disable the root login. Without root, attackers must first guess a user name configured as a sudoer as well as the user password. See for example OpenSSH#Deny.
The account can be locked via passwd :
A similar command unlocks root.
Alternatively, edit /etc/shadow and replace the root’s encrypted password with «!»:
To enable root login again:
kdesu
kdesu may be used under KDE to launch GUI applications with root privileges. It is possible that by default kdesu will try to use su even if the root account is disabled. Fortunately one can tell kdesu to use sudo instead of su. Create/edit the file
or use the following command:
Alternatively, install kdesudo AUR , which has the added advantage of tab-completion for the command following.
Harden with sudo example
Let us say you create 3 users: admin, devel, and joe. The user «admin» is used for journalctl, systemctl, mount, kill, and iptables; «devel» is used for installing packages, and editing config files; and «joe» is the user you log in with. To let «joe» reboot, shutdown, and use netctl we would do the following:
Edit /etc/pam.d/su and /etc/pam.d/su-l Require user be in the wheel group, but do not put anyone in it.
Limit SSH login to the ‘ssh’ group. Only «joe» will be part of this group.
Add users to other groups.
Set permissions on configs so devel can edit them.
With this setup, you will almost never need to login as the Root user.
«joe» can connect to his home WiFi.
«joe» can not use netctl as any other user.
When «joe» needs to use journalctl or kill run away process he can switch to that user.
But «joe» cannot switch to the root user.
If «joe» want to start a gnu-screen session as admin he can do it like this:
Configure sudo using drop-in files in /etc/sudoers.d
sudo parses files contained in the directory /etc/sudoers.d/ . This means that instead of editing /etc/sudoers , you can change settings in standalone files and drop them in that directory. This has two advantages:
- There is no need to edit a sudoers.pacnew file;
- If there is a problem with a new entry, you can remove the offending file instead of editing /etc/sudoers (but see the warning below).
The format for entries in these drop-in files is the same as for /etc/sudoers itself. To edit them directly, use visudo -f /etc/sudoers.d/somefile . See sudoers(5) § Including other files from within sudoers for details.
The files in /etc/sudoers.d/ directory are parsed in lexicographical order, file names containing . or
are skipped. To avoid sorting problems, the file names should begin with two digits, e.g. 01_foo .
Editing files
sudo -e or sudoedit lets you edit a file as another user while still running the text editor as your user.
This is especially useful for editing files as root without elevating the privilege of your text editor, for more details read sudo(8) § e .
Note that you can set the editor to any program, so for example one can use meld to manage pacnew files:
Enable insults
Users can enable insults easter egg in sudo by adding the following line in sudoers file with visudo .
Upon entering an incorrect password this will replace Sorry, try again. message with humorous insults.
Troubleshooting
SSH problem without TTY
This article or section is a candidate for merging with #Configuration.
SSH does not allocate a tty by default when running a remote command. Without a allocated tty, sudo cannot prevent the password from being displayed. You can use ssh’s -t option to force it to allocate a tty.
The Defaults option requiretty only allows the user to run sudo if they have a tty.
Permissive umask
This article or section is a candidate for merging with #Configuration.
Sudo will union the user’s umask value with its own umask (which defaults to 0022). This prevents sudo from creating files with more open permissions than the user’s umask allows. While this is a sane default if no custom umask is in use, this can lead to situations where a utility run by sudo may create files with different permissions than if run by root directly. If errors arise from this, sudo provides a means to fix the umask, even if the desired umask is more permissive than the umask that the user has specified. Adding this (using visudo ) will override sudo’s default behavior:
This sets sudo’s umask to root’s default umask (0022) and overrides the default behavior, always using the indicated umask regardless of what umask the user as set.
Источник
How to Use the sudo Command in Linux
Home » SysAdmin » How to Use the sudo Command in Linux
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.
- 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.
Examples of sudo in Linux
Basic Sudo Usage
1. Open a terminal window, and try the following command:
2. You should see an error message. You do not have the necessary permissions to run the command.
3. Try the same command with sudo :
4. Type your password when prompted. The system executes the command and updates the repositories.
Run Command as a Different User
1. To run a command as a different user, in the terminal, enter the following command:
2. The system should display your username. Next, run the following command:
3. Enter the password for [different_username] , and the whoami command will run and display the different user.
Switch to Root User
This command switches your command prompt to the BASH shell as a root user:
Your command line should change to:
The hostname value will be the network name of this system. The username will be the current logged-in username.
Execute Previous Commands with sudo
The Linux command line keeps a record of previously executed commands. These records can be accessed by pressing the up arrow. To repeat the last command with elevated privileges, use:
This also works with older commands. Specify the historical number as follows:
This example repeats the 6th entry in history with the sudo command.
Run Multiple Commands in One Line
String multiple commands together, separated by a semicolon:
Add a String of Text to an Existing File
Adding a string of text to a file is often used to add the name of a software repository to the sources file, without opening the file for editing. Use the following syntax with echo, sudo and tee command:
Note: This would add the Nginx software repositories to your system.
You should now understand the sudo command, and how to use it. Next, learn the difference between the sudo and su command.
Источник