How to install sudo
How to install sudo
Установка sudo в Debian 10
Debian 10 вышел в релиз. Это прекрасная новость не только для постоянных пользователей этого дистрибутива, но и для всего сообщества Linux. Однако, если вы установили дистрибутив, то скорее всего заметили, что обычный пользователь не может использовать sudo.
Если вы попытаетесь использовать sudo после установки системы, то получите ошибку имя_пользователя is not in the sudoers file. This incident will be reported. Это значит, что несмотря на то, что утилита sudo установлена, вы все ещё не можете ею пользоваться. В этой статье мы рассмотрим как исправить эту проблему.
Что такое sudo?
Независимо от дистрибутива Linux, на компьютере есть разные пользователи. Каждый из них имеет определенные роли и разрешения. Допустим, нужно установить какой-то пакет в Debian. Выполнить эту операцию сможет только пользователь с правами root. Другие пользователи не имеют доступа к этому действию.
Настройка sudo в Debian 10
Сначала установим утилиту sudo если она ещё не установлена, а для этого нужно иметь права пользователя root. Это очень важно. Откройте терминал, или подключитесь к серверу удаленно через SSH и переключитесь на пользователя root:
Утилита запросит пароль пользователя root. Теперь можно устанавливать sudo из репозиториев Debian:
apt install sudo
Утилита установится быстро. После этого посмотрите содержимое файла /etc/sudoers:
В файле просто разобраться. В разделе спецификаций привилегий пользователя вы найдете строку, подобную этой:
%sudo ALL=(ALL:ALL) ALL
Если она есть, то вы можете просто добавить текущего пользователя в группу sudo и тогда он сможет использовать утилиту sudo. Например:
Или в этот файл можно добавить отдельную строчку для своего пользователя. Она будет выглядеть вот так:
имя_вашего_пользователя ALL=(ALL:ALL) ALL
Для сохранения изменений нажмите клавишу Esc и выполните команду :w, а затем :q. Не зависимо от выбранного вами способа настройки, после завершения вы можете пользоваться командой sudo.
How to install sudo on Debian or Ubuntu Linux
Whether you are using Debian 11 Bullseye, 10 Buster, Ubuntu 20.04, 18.04, 22.04, or any other minimal server version of the same base, here are there steps to install sudo Debian Linux.
The command sudo, we used before other program calls to execute them. The key purpose of it is to authorize the users to run the program on behalf of and with the rights of another user to perform tasks that are reserved for administrators.
When we run the command with sudo, it asks for the password of the current user before executing the program. This checks whether the user that entered the command is the group of authorized users defined in the /etc/sudoers file or not. The target user is root assumed by default.
Under Debian, in /etc/sudoers all members of the group are sudo and allowed by default to become the user root and thus to receive root rights. The user or users created during installation belong to the group sudo by default.
In GUI desktop environments such as GNOME or KDE, root rights are sometimes automatically requested for a certain program for certain tasks by giving a graphical dialogue box. For example, you are automatically asked for your password for a program installation or upgrading system graphically, so that APT receives root rights and can install the program. In many cases, sudo no longer needs to be called manually.
Easy way to understand what sudo is for-
Command to Install sudo on Debian Linux Minimal server
Well, sudo is already in the Debian system most of the time; however, in minimal Debian installation such as Debian on Docker, the sudo will be missing. Hence, to create any other user and use that to install some software without giving root access for all the commands, we have to install sudo manually using the command line. Here are the steps to follow.
This article assumes that you already have root user access because without that we cannot install “sudo” or any other packages.
1. Apt update cache
First, run the system update command to refresh the APT repositories cache. This is necessary because many times after installing a fresh minimal Debian or Ubuntu Linux, it won’t recognize any packages to install. It is because there is no list of packages in the cache, that the system can identify to install.
2. Command to install sudo on Debian or Ubuntu server
You have the updated minimal Debian or Ubuntu server, now we can easily use the APT package manager command to install the “sudo” without the help of any additional repository as it is already available in the base repo of Debian.
How to Install and Manage Sudo
Sudo is a linux command which can be used to grant root-level access to authorized users without requiring these users to login as the root user. This is useful for securing a server by disabling root access and instead granting sudo access to select users.
In this article, we’ll outline how to install sudo and add users to the sudo group.
How to Install Sudo
If sudo is not yet installed on your server, follow these commands in order to install sudo on Debian, CentOS, or FreeBSD:
Debian
CentOS
How to Add Users to the Sudo Group
Debian / CentOS / FreeBSD
Begin by adding the user account to the server if it does not already exist:
adduser mynewusername
Then you can add the user to the sudo or wheel group:
Debian
CentOS
Testing Sudo Access
You have now installed sudo and added the user to the sudo group. You can test sudo access by switching into the new user using the su command executing:
sudo echo “hello world”
You will be prompted to enter the password of the user, and the screen will display hello world when executed successfully:
[email protected]:/root$ sudo echo “hello world”hello world
If the user has not been added to sudo properly, it will display:
[email protected]:/root$ sudo echo “hello world”user is not in the sudoers file. This incident will be reported.
Next Steps
Check out our other Knowledge Base articles including the Top 5 Ways to Secure Your Linux Server.
COMPLETE DIGITAL SERVER SOLUTIONS FOR ALL
Bare Metal Dedicated Servers
A single tenant, physical server allowing you full access to its resources.
Professional Hybrid Servers
Virtualized server platform hosted on enterprise-grade physical servers.
Scalable Cloud Servers
High-performance and highly-available infrastructure.
Managed Colocation
Our next-generation data center facilities.
10+ sudo command examples in Linux [Cheat Sheet]
Table of Contents
Introduction to sudo command
sudo command in Linux stands for Super User DO. It allows you to execute a command as another user, including the superuser. sudo is an efficient way to access the root privileges and execute the command as the root user. With sudo, you can access the root privileges without knowing the root password or logging as the root user. The user needs to have the sudo privileges to run the sudo command.
How to install sudo
In most of the Linux distributions, sudo is pre-installed on the system. However, if you do not find the sudo package on the system, you can install it from the default package management repositories.
To install sudo on CentOS, Fedora, and RHEL
To install sudo on Ubuntu and Debian
Syntax for sudo command
The security policy determines whether or not a user has sudo privileges. The default security policy is sudoers configured in the file /etc/sudoers.
The general syntax for sudo command is as follows:
Some of the options available in sudo command are:
Different examples to use sudo command
1. Use sudo to run command as a root user
By default, when no user is specified, the sudo runs a command as a root user. It is mostly used to run the command which needs root permission.
Sample Output:
When listing the root directory, the permission was denied because only the root user can list the root directory. But, after using the sudo command, we can list the root directory.
Similarly, when you want to install, remove, or update the package in the system, you will need the root privilege. You can use sudo command to install the package without logging in as a root user.
2. Use sudo to run command as a different user
Sample Output:
You can also change the password of another user without logging in.
3. List user privileges with sudo command
Sample Output:
It shows the user golinux can run all the commands with sudo on the system.
As you can see, it does not run the command but only checks where it is located in the system.
4. Display privileges for another user with sudo command
Sample Output:
As you can see, the user deepak does not have sudo privileges but the root user can run all the commands.
5. sudo command to add a user to the sudo group
When you add a user to the sudo group, that user will be able to run all commands with sudo. You can add a user to the sudo group with the following command on Ubuntu and Debian.
Sample Output:
On RHEL, CentOS, and Fedora, you can use:
6. sudo command to add users to the sudoers file
The user and group sudo privileges are defined in the /etc/sudoers file. The user who is listed in the sudoers file has sudo privileges and can run sudo command. You can add a user in the sudoers file by using visudo command.
Sample Output:
You need to add [username] ALL=(ALL:ALL) ALL on the User privilege specification as shown in the image below.
7. Run command in the background with sudo
8. Update sudoers files using sudo command
Sample Output:
You can only edit files on the directory which is non-writable. It opens a nano editor to edit a file.
This will create a new sudo rule inside /etc/sudoers.d based on the content added in this file. Now if you didn’t followed proper syntax while adding sudo rules, then after svaing the file, you won’t be able to access the file again or you may not able to save the file itself. Here is a sample error when I intentionally gave a wrong syntax in my sudoers file
9. sudo command to update the user’s cached credentials
Sample Output:
It does not print any output but displays an error if the user does not have sudo privileges.
10. sudo command to invalidate user’s cached credentials
Sample Output:
11. sudo command to remove the user’s timestamp completely
sudo command vs su command
Both sudo and su command are used to access the privileges of other accounts, including the root. su command is used to switch the user account whereas sudo command is used to run the command as the root user or a different user. Generally, with su command, you will need the password of the target user. But, sudo asks for the password of the current user.
For more details on su command, please read 9 su command examples in Linux [Cheat Sheet]
Conclusion
In this tutorial, we discussed the usages and the most common examples of sudo command in Linux. We hope you have learned how to use sudo command and execute the commands as another user with sudo privileges. If you still have any confusion, do let us know in the comment section.
How To: Setup sudo in Debian
Apparently, Debian installer doesn’t install or activate sudo by default. This means that sudo command is not found the only privilege escalation method available is becoming root via su command. Since I like and use sudo daily, I decided to install and setup it on Debian VM.
Install sudo package in Debian
That’s the very first step you’ll need to do: use apt to install sudo. You need to become root before you do it, of course (so you must know root user password for your Debian install):
Configure /etc/sudoers File
/etc/sudoers is the main configuration file for sudo command. It contains list of users and groups that are allowed to become root (or become other users by invoking su command as root).
Here’s the default file in Debian 10 Buster:
I’ve highlighted the 3 most important elements of this file at this early stage:
This is the line that allows you to debug sudo commands as root user.
At this means that any user that belongs to group sudo will also be allowed to use sudo commands:
Finally, this part includes additional configuration files from /etc/sudoers.d directory:
… this means you don’t have to edit /etc/sudoers file but instead can create a specific file in /etc/sudoers.d and name it self-descriptively, like:
meaning, that this file will contain usernames and privileges required by web-server admins (usually commands like stopping/starting Apache or nginx webserver).
Since this is a very basic tutorial, we don’t have to edit the file at all – just need to add our user (mine is greys, as you remember) to the sudo group and check.
Add user to sudo group
Step 1: let’s make sure sudo is not accessible before we begin
This needs to be run as your regular user, not as root:
Let’s check my groups just to be sure there’s no sudo among them:
Step 2: add user to sudo group
Excellent, now it’s time to add user greys to the group sudo (we must become root again to run usermod command)
As you can see, I’m now a member of the sudo group!
Step 3: Log out and log back in for group membership to be recognised
Now you need to disconnect from your server or desktop session and log in again, so that your group membersip is recognised. One reconnected, check your groups with id command and try sudo again:
so yes, we’re a member of sudo group now… This is the moment of truth! Let’s try to become root: