Linux what is sudo command

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

Источник

Linux command line basics: sudo

Image by Pixabay

More Linux resources

When I first started learning the Linux command line, I found myself memorizing commands for specific scenarios. Even if it wasn’t the best command for the job, I had my way of doing things, and that worked for me. As I started working in a more professional environment around people with years of experience and knowledge, I discovered that just because I could use a command did not mean that I understood the command. Sometimes, just knowing how isn’t good enough. It helps to understand what is going on behind the scenes and why you use specific arguments, flags, and objects. The sudo command is one that I didn’t use often before. This choice is unthinkable now, and honestly, it makes me laugh at myself for assuming I knew what I was doing. I’ll explain this later on; for now, let’s take a look at what the sudo command is, why it’s important, and how to configure it.

Читайте также:  Права root пользователю линукс

Do you know those crime TV scenes where a plainclothes detective walks up and the uniformed officer stops them from entering the area until they flash their badge? We’ve all seen this drama unfold over the years, from the yellow tape to the pouring rain and the cliché trench coats, but what happens next? The uniformed officer takes a look, realizes that this person belongs on the scene, and lets them pass. Sudo is your badge. It’s your «golden ticket,» your security clearance, and your permission to do as you please. Metaphor aside, sudo is your elevated privilege.

Sudo stands for «superuser do» and is the master key to your high-privilege admin tasks. Have you ever tried to edit a config file only to receive «Permission Denied?» (The /etc/hosts file comes to mind.) If so, that was because your user account did not have access to that file. You need root or sudoer access. Previously, back when I was doing things «my way,» I used to always use the su command (switch user) and would log in as root for these tasks. While this method works, it isn’t the best way to accomplish the needed task in most cases.

Think about this: You su to root to edit a file, but you forget to switch back to your user account afterward. At this point, a simple command line error could cost you dearly as an administrator. I saw a colleague blow away the root directory of a back-end storage server for the state of New York due to this simple oversight. Thankfully, the data and his career were recoverable!

So how do I use sudo ?

Simply preface the intended command with sudo . You will then be prompted for a password (you need to enter your user account password, not root’s). For example, if you want to edit an important configuration file, you might use vi /etc/sudoers :

Источник

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.

Читайте также:  Настройка vpn mac os windows

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.

Источник

Команда sudo в Linux

Если вы новый пользователь Linux, то, наверное, уже заметили, что здесь почти для всех серьёзных настроек или операций с системой нужны права суперпользователя. Пользователям 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 — выводит версию утилиты;
  • — означает, что следующие опции обрабатывать не нужно.
Читайте также:  Chameleon clock для windows x64

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

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

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

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

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

sudo -u sergiy whoami

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

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

Без опции -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.

Источник

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