What is sudo group in linux

What Is Sudo Command in Linux?

sudo or superuser do is a utility used on Linux, BSD, and Unix systems that provides the running command with root or Administrator privileges. Not every user needs to have root privileges but in some cases needs to run commands with root privileges. We can use sudo to run some specific or all provided commands and edit files with the root privileges.

sudo Configuration File sudoers

sudo command is configuration is stored /etc/sudoers file. This file can be only viewed and edit with root privileges. We can edit this just with visudo command like below.

We can see that there is a different part of the sudoers configuration file where default values, user and group privileges are provided.

Configuration Syntax

We can use the following syntax in order to create a sudo configuration about the given user or group.

  • USER is the user who can run the given command on the given host
  • HOSTLIST is the hosts where given commands can be run
  • COMMANDLIST is the commands can be run. Multiple commands can be delimited with the comma.

Specify A User To Run Sudo Command

We can add a user to run a specific command with root privileges. In this example, we will add user ismail to run command visudo with root privileges.

Passwordless Sudo Command

We can provide sudo command to the given user without any password. We will use NOPASSWD configuration like below which will disable password for the user ismail .

List Available Commands

We can list available commands with the -l option which will list currently used root privileged commands the current user can execute.

Run Command with Root Privileges

In this example, we will run commands with root privileges by using sudo command. We will run ls command in the /root directory which is completely owned by root and only used by the root user.

Edit File with Root Privileges

We also edit files with the root privileges by using sudo command. We will edit the /etc/passwd file with the vim command like below.

Difference Between sudo and su

su command is used to login as root user on the other side sudo command just runs given command as root in the current user sessions. While running sudo command the user name will be also logged but with the sudo command just the root user name will be logged. The best way to

Источник

Команда sudo в Linux

Если вы новый пользователь Linux, то, наверное, уже заметили, что здесь почти для всех серьёзных настроек или операций с системой нужны права суперпользователя. Пользователям Windows такой подход тоже должен быть знаком, когда вы устанавливаете программы или меняете системные настройки, операционная система просит подтвердить выполнение программы от имени администратора.

Читайте также:  Как снести ubuntu с windows

В Linux такой возможности нет, но зато есть команда sudo, которая позволяет вам запускать программы от имени других пользователей, а также от имени суперпользователя. На сайте уже есть несколько материалов про работу с ней, но нет подробной статьи про опции самой команды и её синтаксис. Эта тема и будет раскрыта сейчас. Дальше мы рассмотрим, что представляет из себя команда sudo Linux, но начнем с её синтаксиса.

Синтаксис sudo

Синтаксис команды очень прост:

$ sudo опции программа параметры

Так вы можете выполнить абсолютно любую команду Linux. Достаточно написать перед ней команду sudo. По умолчанию sudo запускает переданную ей команду от имени суперпользователя. Если вы хотите добавить какие-либо настройки или использовать другого пользователя, нужно указывать опции.

Опции sudo

  • -A или —askpass — по умолчанию sudo спрашивает пароль пользователя в терминале. Если задана эта опция, утилита попробует использовать графическую утилиту для запроса пароля.
  • -b или —background — запускает переданную программу в фоновом режиме;
  • -C или —close-from — опции нужно передать число больше трёх. Она позволяет закрыть для программы все файловые дескрипторы, кроме стандартного ввода и вывода;
  • -E или —preserve-env — позволяет передать переменные окружения текущего пользователя выполняемой программе. Также можно передать этой опции список переменных, которые нужно разрешить;
  • -e или —edit — позволяет редактировать файл вместо запуска команды. Файл копируется во временный каталог, редактируется с помощью редактора, установленного в системе по умолчанию, и если были изменения, записывается обратно с теми самыми правами;
  • -g — запустить команду с указанной группой вместо группы пользователя, от имени которого запускается программа;
  • -h — выполнить команду от имени другого хоста;
  • -H или —set-home — установить домашний каталог;
  • -i или —login — позволяет авторизоваться в консоли от имени другого пользователя. Будет выбран его домашний каталог, а также загружены все переменные окружения;
  • -k — по умолчанию, sudo сохраняет пароль и некоторое время после выполнения команды, вы можете выполнить ещё раз, без ввода пароля. Эта опция отключает такую возможность;
  • -l или —list — позволяет вывести список доступных команд для удалённых пользователей;
  • -n или —non-interactive — не интерактивный режим, если будет необходимо ввести пароль, программа выдаст ошибку;
  • -p или —prompt — использовать своё приглашение для ввода пароля;
  • -r или —role — выполнить программу с контекстом SELinux, у которого есть указанная роль;
  • -S — использовать стандартный поток ошибок для запроса пароля;
  • -s или —shell — позволяет запустить указанный командный интерпретатор;
  • -U или —User — вместе с опцией -l позволяет посмотреть привилегии для пользователя;
  • -T или —timeout — позволяет установить время выполнения команды, если время истечёт раньше, чем завершится команда, то она будет завершена принудительно;
  • -u — позволяет указать, от имени какого пользователя нужно выполнять программу;
  • -V — выводит версию утилиты;
  • — означает, что следующие опции обрабатывать не нужно.

Это основные опции, которые вы можете использовать. А теперь давайте перейдём к примерам использования команды.

Примеры использования sudo

1. Запуск программы

Самый частый пример использования sudo — выполнение программы от имени суперпользователя. Для этого достаточно написать sudo перед именем программы:

Если вы хотите выполнить программу не от имени root, а от имени другого пользователя, то можно использовать опцию -u, например:

sudo -u sergiy whoami

2. Переменные окружения

По умолчанию, команда sudo не передаёт запускаемой утилите переменные окружения текущего пользователя. А когда вы запускаете графическое приложение, то ему нужна переменная DISPLAY для доступа к графическому серверу. В последних версиях Ubuntu всё немного по другому, но все же эта возможность sudo актуальна. Чтобы передать переменные просто используйте опцию -E:

Читайте также:  Orcad для windows 10 x64

Без опции -E программа получает только 18 стандартных переменных, а с опцией — все доступные.

Также вы можете указать список переменных, которые нужно передать:

3. Авторизация от имени другого пользователя

С помощью sudo вы также можете авторизоваться от имени другого пользователя. Для этого используйте опцию -i:

По умолчанию вы будете авторизованы как суперпользователь. Ещё здесь можно указать пользователя, от имени которого вы хотите авторизоваться:

sudo -i -u sergiy

4. Командный интерпретатор

Если у вас в системе установлено несколько командных интерпретаторов, например, не только bash, но и zsh, то вы можете авторизоваться от имени другого пользователя и указать, какую именно оболочку вы хотите использовать. Для этого укажите опция -s:

5. Редактирование файлов

Когда вам необходимо отредактировать системный файл, вы пишите sudo vim или sudo nano. Вместо этого можно использовать опцию -e или команду sudoedit. Она открывает файл для редактирования, редактором, установленным в системе по умолчанию. Например, у меня это vim. Чтобы отредактировать /etc/group с правами суперпользователя достаточно выполнить:

sudo -e /etc/group

Утилита узнает, каким редактором нужно пользоваться из переменной окружения EDITOR.

6. Запуск в фоне

Чтобы запустить программу в фоне с помощью sudo можно использовать опцию -b. Например, запускаем OpenVPN в фоновом режиме:

sudo -b openvpn -с /путь/к/конфигурационному.файлу

7. Просмотр полномочий

Вам необязательно редактировать конфигурационный файл, чтобы понять, какие настройки для sudo разрешены, а какие нет. Для этого можно выполнить команду с опцией -l. Утилита выведет список разрешённых команд или ALL в случае, если разрешено всё:

Выводы

Теперь вы знаете, что из себя представляет команда sudo Linux. Здесь мы рассмотрели только общие примеры её использования. Если вы хотите прочитать более подробно про её настройку, смотрите статью настройка sudo в Linux.

Источник

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.

Источник

Оцените статью