- Linux sudo command
- Description
- Syntax
- Options
- Return values
- Security notes
- Environment variables
- Examples
- Related commands
- ИТ База знаний
- Полезно
- Навигация
- Серверные решения
- Телефония
- Корпоративные сети
- Как использовать команду sudo в Linux
- Как использовать команду sudo
- Установка sudo
- Синтаксис
- Опции
- Предоставление привилегий sudo
- RedHat и CentOS
- Debian и Ubuntu
- Использование visudo и группы sudoers
- Тайм-аут пароля sudo
- Примеры sudo в Linux
- Основное использование Sudo
- Выполнить команду от имени другого пользователя
- Переключиться на root пользователя
- Выполнить предыдущие команды с помощью sudo
- Запуск нескольких команд в одной строке
- Добавить строку текста в существующий файл
- Заключение
- Полезно?
- Почему?
Linux sudo command
On Unix-like operating systems, the sudo command («switch user, do») allows a user with proper permissions to execute a command as another user. By default, sudo executes commands as root.
This page describes the Linux version of sudo.
Description
sudo allows a permitted user to execute a command as another user, according to specifications in the /etc/sudoers file. The real and effective uid and gid of the issuing user are then set to match those of the target user account as specified in the passwd file.
By default, sudo requires that users authenticate themselves with a password. By default, this is the user’s password, not the root password itself.
Once a user is authenticated, a timestamp is recorded and the user may use sudo without a password for a short time (5 minutes, unless configured differently in sudoers). This timestamp can be renewed if the user issues sudo with the -v flag.
If a user not listed in sudoers tries to run a command using sudo, it is considered an unsuccessful attempt to breach system security and mail is sent to the proper authorities, as defined at configure time or in the sudoers file. The default authority to be notified of unsuccessful sudo attempts is root. Note that the mail isn’t sent if an unauthorized user tries to run sudo with the -l or -v flags; this allows users to determine for themselves whether or not they are allowed to use sudo.
sudo can log both successful and unsuccessful attempts (and errors) to syslog, a unique log file, or both. By default, sudo will log to syslog but this can be changed at configure time or in the sudoers file.
To edit the sudoers file, use the visudo command.
Syntax
Options
-V | The -V (version) option causes sudo to print the version number and exit. If the invoking user is already root, the -V option prints out a list of the defaults sudo was compiled with and the machine’s local network addresses. |
-l | The -l (list) option prints out the commands allowed (and forbidden) the user on the current host. |
-L | The -L (list defaults) option lists out the parameters set in a Defaults line with a short description for each. This option is useful in conjunction with grep. |
-h | The -h (help) option causes sudo to print a usage message and exit. |
-v | If given the -v (validate) option, sudo updates the user’s timestamp, prompting for the user’s password if necessary. This extends the sudo timeout for another 5 minutes (or whatever the timeout is set to in sudoers) but does not run a command. |
-k | The -k (kill) option to sudo invalidates the user’s timestamp by setting the time on it to the epoch. The next time sudo is run a password will be required. This option does not require a password and was added to allow a user to revoke sudo permissions from a .logout file. |
-K | The -K (sure kill) option to sudo removes the user’s timestamp entirely. Likewise, this option does not require a password. |
-b | The -b (background) option tells sudo to run the given command in the background. Note that if you use the -b option you cannot use shell job control to manipulate the process. |
-p | The -p (prompt) option allows you to override the default password prompt and use a custom one. The following percent (‘%‘) escapes are supported: |
%u is expanded to the invoking user’s login name;
%U is expanded to the login name of the user the command will run as (which defaults to root);
%h is expanded to the local hostname without the domain name;
%H is expanded to the local hostname including the domain name (only if the machine’s hostname is fully qualified or the «fqdn» sudoers option is set);
%% (two consecutive % characters) are collapsed into a single % character.
Return values
Upon successful execution of a program, the return value from sudo will be the return value of the program that was executed.
Otherwise, sudo quits with an exit value of 1 if there is a configuration/permission problem or if sudo cannot execute the given command. In the latter case the error string is printed to stderr. If sudo cannot stat one or more entries in the user’s PATH an error is printed on stderr. (If the directory does not exist or if it’s not a directory, the entry is ignored and no error is printed.) This should not happen under normal circumstances. The most common reason for stat to return «permission denied» is if you are running an auto-mounter and one of the directories in your PATH is on a machine that is currently unreachable.
Security notes
sudo tries to be safe when executing commands. Variables that control how dynamic loading and binding is done can subvert the program that sudo runs. To combat this, some system-specific environment variables are removed from the environment that is passed on to the commands that are executed. Other variables that sudo removes from the environment include:
- IFS
- ENV
- BASH_ENV
- KRB_CONF
- KRBCONFDIR
- KRBTKFILE
- KRB5_CONFIG
- LOCALDOMAIN
- RES_OPTIONS
- HOSTALIASES
- NLSPATH
- PATH_LOCALE
- TERMINFO
- TERMINFO_DIRS
- TERMPATH
as they too can pose a threat. If the TERMCAP variable is set and is a pathname, it too is ignored. Additionally, if certain variables contain the / or % characters, they are ignored.
If sudo was compiled with SecurID support, the VAR_ACE, USR_ACE and DLC_ACE variables are cleared as well. The list of environment variables that sudo clears is contained in the output of sudo -V when run as root.
To prevent command spoofing, sudo checks «.» and «» (both denoting current directory) last when searching for a command in the user’s PATH (if one or both are in the PATH). Note, however, that the actual PATH environment variable is not modified and is passed unchanged to the program that sudo executes.
For security reasons, if your OS supports shared libraries and does not disable user-defined library search paths for setuid programs (most do), either use a linker option that disables this behavior or link sudo statically.
sudo checks the ownership of its timestamp directory (/var/run/sudo by default) and ignore the directory’s contents if it’s not owned by root and only writable by root. On systems that allow non-root users to give away files via chown, if the timestamp directory is located in a directory writable by anyone (e.g.: /tmp), it is possible for a user to create the timestamp directory before sudo is run. However, because sudo checks the ownership and mode of the directory and its contents, the only damage that can be done is to «hide» files by putting them in the timestamp dir. This is unlikely to happen since once the timestamp dir is owned by root and inaccessible by any other user the user placing files there would be unable to get them back out. To get around this issue, you can use a directory that is not world-writable for the timestamps (/var/adm/sudo for instance) or create /var/run/sudo with the appropriate owner (root) and permissions (0700) in the system startup files.
sudo will not honor timestamps set far in the future. Timestamps with a date greater than current_time + 2 * TIMEOUT is ignored and sudo will log and complain. This is done to keep a user from creating his/her own timestamp with a bogus date on systems that allow users to give away files.
Please note that sudo only logs the command it explicitly runs. If a user runs a command such as «sudo su» or «sudo sh«, subsequent commands run from that shell are not logged, nor will sudo‘s access control affect them. The same is true for commands that offer shell escapes (including most editors). Because of this, care must be taken when giving users access to commands via sudo to verify that the command does not inadvertently give the user an effective root shell.
Environment variables
PATH | Set to a sane value if SECURE_PATH is set |
SHELL | Used to determine shell to run with -s option |
USER | Set to the target user (root unless the -u option is specified) |
HOME | In -s or -H mode (or if sudo was configured with the —enable-shell-sets-home option), set to home directory of the target user. |
SUDO_PROMPT | Used as the default password prompt |
SUDO_COMMAND | Set to the command run by sudo |
SUDO_USER | Set to the login of the user who invoked sudo |
SUDO_UID | Set to the uid of the user who invoked sudo |
SUDO_GID | Set to the gid of the user who invoked sudo |
SUDO_PS1 | If set, PS1 will be set to its value |
Examples
Restart the system; run the shutdown command as root.
List the contents of the /home/otheruser/Documents directory as the user hope.
Create a new directory with the mkdir command, as the user hope, with hope’s current group set to otherusers. hope must be a member of the otherusers group.
Extend/reset sudo‘s automatic authentication timeout, allowing you to continue issuing sudo commands without entering a password.
«Kill» sudo authentication for the current user. The next sudo command requires a password.
Related commands
su — Become the superuser or another user.
visudo — Edit the sudoers file, which defines who can run sudo.
Источник
ИТ База знаний
Курс по Asterisk
Полезно
— Узнать IP — адрес компьютера в интернете
— Онлайн генератор устойчивых паролей
— Онлайн калькулятор подсетей
— Калькулятор инсталляции IP — АТС Asterisk
— Руководство администратора FreePBX на русском языке
— Руководство администратора Cisco UCM/CME на русском языке
— Руководство администратора по Linux/Unix
Навигация
Серверные решения
Телефония
FreePBX и Asterisk
Настройка программных телефонов
Корпоративные сети
Протоколы и стандарты
Как использовать команду sudo в Linux
Sudo означает SuperUser DO и используется для доступа к файлам и операциям с ограниченным доступом. По умолчанию Linux ограничивает доступ к определенным частям системы, предотвращая компрометацию конфиденциальных файлов.
Мини — курс по виртуализации
Знакомство с VMware vSphere 7 и технологией виртуализации в авторском мини — курсе от Михаила Якобсена
Команда sudo временно повышает привилегии, позволяя пользователям выполнять конфиденциальные задачи без входа в систему как пользователь root . В этом руководстве вы узнаете, как использовать команду sudo в Linux с примерами.
Как использовать команду sudo
Установка sudo
Пакет sudo установлен в большинстве дистрибутивов Linux.
Чтобы проверить есть ли у вас эта комманда введите sudo . Вы увидите справочное сообщение или сообщение о том что комнада не найдена.
Чтобы установить sudo используйте для Ubuntu и Debian:
или для CentOS и Fedora
sudo была разработана как способ временного предоставления пользователю административных прав. Чтобы заставить ее работать, используйте sudo перед ограниченной командой, которую можно выполнить только из под рута. Тогда система запросит ваш пароль. После его ввода система запускает команду.
Синтаксис
Опции
sudo можно использовать с дополнительными параметрами:
- -h — отображает синтаксис и параметры команды
- -V — отображает текущую версию приложения sudo
- -v — обновить лимит времени на sudo без запуска команды
- -l — перечисляет права пользователя или проверяет конкретную команду
- -к — завершить текущие привилегии sudo
Дополнительные параметры можно найти с помощью ключа -h .
Примечание. Оставаться в системе как администратор ставит под угрозу безопасность сервера. Раньше администраторы использовали su (substitute user) для временного переключения на учетную запись администратора. Однако для команды su требуется вторая учетная запись пользователя и пароль, что не всегда возможно.
Когда используется команда sudo , в системные журналы заносится метка времени. Пользователь может запускать команды с повышенными привилегиями в течение короткого времени (по умолчанию 15 минут). Если пользователь, не принадлежащий к sudo группе, пытается использовать команду sudo , это регистрируется как событие безопасности.
Предоставление привилегий sudo
Для большинства современных дистрибутивов Linux пользователь должен входить в группу sudo, sudoers или wheel, чтобы использовать команду sudo . По умолчанию однопользовательская система предоставляет своему пользователю права sudo . Система или сервер с несколькими учетными записями пользователей могут исключать некоторых пользователей из привилегий sudo .
Рассмотрим как добавить пользователя в эту группу.
RedHat и CentOS
В Redhat и CentOS wheel группа контролирует пользователей sudo . Добавьте пользователя в группу wheel с помощью следующей команды:
Замените [username] фактическим именем пользователя. Возможно, вам потребуется войти в систему как администратор или использовать команду su .
Debian и Ubuntu
В Debian и Ubuntu группа sudo (sudo group) контролирует пользователей sudo . Добавьте пользователя в группу sudo с помощью следующей команды:
Использование visudo и группы sudoers
В некоторых современных версиях Linux пользователи добавляются в файл sudoers для предоставления привилегий. Это делается с помощью команды visudo .
Используйте команду visudo для редактирования файла конфигурации:
Это откроет /etc/sudoers для редактирования. Чтобы добавить пользователя и предоставить полные права sudo , добавьте следующую строку:
Сохраните и выйдите из файла.
Вот разбивка предоставленных привилегий sudo :
Примечание. Проще добавить пользователя в группу sudo или wheel, чтобы предоставить права sudo . Если вам нужно отредактировать файл конфигурации, делайте это только с помощью visudo . Приложение visudo предотвращает сбои, ошибки и неправильные настройки, которые могут нарушить работу вашей операционной системы.
Тайм-аут пароля sudo
По умолчанию sudo просит вас ввести пароль после нескольких минут бездействия. Изменить это время ожидания по умолчанию, можно отредактировав файл sudoers с помощью visudo и измените время ожидания, добавив строку как в примере, где 10 — это время ожидания, указанное в минутах:
Если вы хотите изменить время ожидания для определенного пользователя, то добавьте имя пользователя.
Примеры sudo в Linux
Основное использование Sudo
1. Откройте окно терминала и попробуйте выполнить следующую команду:
2. Вы должны увидеть сообщение об ошибке. У вас нет необходимых разрешений для запуска команды.
3. Попробуйте ту же команду с sudo:
4. При появлении запроса введите свой пароль. Система выполнит команду и обновит репозитории.
Выполнить команду от имени другого пользователя
1. Чтобы запустить команду от имени другого пользователя, введите в терминале следующую команду:
2. Система должна отображать ваше имя пользователя. Затем выполните следующую команду:
3. Введите пароль для другого пользователя, и команда whoami запустится и отобразит другого пользователя.
Переключиться на root пользователя
Эта команда переключает вашу командную строку на оболочку BASH от имени пользователя root :
Ваша командная строка должна измениться на:
Значение имени хоста будет сетевым именем этой системы. Имя пользователя будет текущим именем пользователя, вошедшим в систему.
Выполнить предыдущие команды с помощью sudo
В командной строке Linux хранятся записи о ранее выполненных командах. Доступ к этим записям можно получить, нажав стрелку вверх. Чтобы повторить последнюю команду с повышенными привилегиями, используйте:
Это также работает со старыми командами. Укажите исторический номер следующим образом:
В этом примере повторяется 6-я запись в истории с командой sudo.
Запуск нескольких команд в одной строке
Соедините несколько команд вместе, разделенных точкой с запятой:
Добавить строку текста в существующий файл
Добавление строки текста в файл часто используется для добавления имени репозитория программного обеспечения к исходному файлу без открытия файла для редактирования. Используйте следующий синтаксис с командами echo , sudo и tee :
Заключение
Теперь вы узнали про команду sudo и про то, как ее использовать.
Онлайн курс по Linux
Мы собрали концентрат самых востребованных знаний, которые позволят тебе начать карьеру администратора Linux, расширить текущие знания и сделать уверенный шаг к DevOps
Полезно?
Почему?
😪 Мы тщательно прорабатываем каждый фидбек и отвечаем по итогам анализа. Напишите, пожалуйста, как мы сможем улучшить эту статью.
😍 Полезные IT – статьи от экспертов раз в неделю у вас в почте. Укажите свою дату рождения и мы не забудем поздравить вас.
Источник