В чем отличие команд «sudo -i» и «sudo su -»?

sudo su — полностью выполняется логин от имени рута.
sudo -i логин эмулируется.
Внешне разница выглядит как то так:
как видно — при sudo su — выполнились все файлы инициализации рута, система вывела информацию о предыдущих логинах, при sudo -i — нет
ну и environment не совпадают.
what is the sudo -i command [duplicate]
What does the sudo -i command do and in which situations would it be used. read it using the man sudo command but i’m looking for a more diluted discription to help me understand better.
2 Answers 2
sudo lets you run commands in your own user account with root privileges. su lets you switch user so that you’re actually logged in as root.
sudo -s runs a shell with root privileges. sudo -i does this as well, but also acquires the root user’s environment.
This means that login-specific resource files such as .profile, .bashrc or .login will be read and executed by the shell.
Basically, you use sudo -i when you know you will be running various commands that need root access and don’t want to run each of them with sudo . To illustrate:
So, after running sudo -i all subsequent commands you run will be run as though you had run them with sudo . You are now logged in as root and no longer need sudo to gain privileges.
The Differences between Su, Sudo Su, Sudo -s and Sudo -i

There are many different ways to get a root session in the Linux terminal. This can create some confusion, as most beginner users who are looking to gain root privileges might not be familiar with how each command can gain root access, how they are different and when these differences matter. Here we take apart each of the many different commands used to gain root access in a terminal, explain how they gain root, when to use them, and everything in between.
Content
The su command substitutes the current user for root in the current shell.

You can switch to any user by typing su and adding a username after it.

This will tell the system to switch (and essentially log out of) the current user to the one specified. Alternatively, the su command can gain root access by entering su without specifying anything after the command.
su is best used when a user wants direct access to the root account on the system. It doesn’t go through sudo or anything like that. Instead, you’re asked to enter the root user’s password, as you’re literally logging into it. Furthermore, other ways of gaining root access do not have the benefit of also getting access to the root home directory and root environment.
Warning: using su is the least safe way to execute a root action. Generally, if you can avoid it, do not use this.
This command passes other commands to the root user directly.

Similar to typing sudo before a command, su -c will run a command as the root user. Instead of simply typing the command, though, you’ll have to put it in quotes.
This is a quickfire way of shooting one command through your terminal with elevated privileges. It’s very useful if sudo somehow is unavailable (it doesn’t come preinstalled in distros like Arch Linux) or fails to work correctly because it’s corrupted.
Since you’re passing something directly to root, if your user and root passwords are different, you’ll have to type your root password to authenticate.
sudo su
This command asks for the current user’s password rather than root.

It’s essentially the same as just running su in the shell, save for one crucial difference: instead of telling the system to “switch users” directly, you’re telling it to run the su command with superuser privileges. When sudo su is run, “.profile,” “.bashrc” and “/etc/profile” will be started, much like running su (or su root ). If any command is run with sudo in front of it, it is given root privileges.
Though there isn’t a large divergence between sudo su and su , the former is still a very useful command for one important reason: when a user is running su to gain root access on a system, they must know the root password. Root is given with sudo su by requesting the current user’s password, which makes it possible to gain root without the root password.
This is useful in situations where you may have forgotten the root password if it’s different from the password for your user account. While you could do this in the meantime, you should still reset the root password at some point.
sudo -i
Using sudo -i is virtually the same as the sudo su command with one exception: it does not directly interact with the root user.

Much like sudo su , the -i flag allows a user to get a root environment without having to know the root account password. sudo -i is also very similar to using sudo su : it’ll read all of the environmental files (“.profile”, etc.) and set the environment inside the shell.
Where it differs from sudo su is that sudo -i is a much cleaner way of gaining root and a root environment without directly interacting with the root user.
To clarify: with sudo su , you’re using more than one root setuid command in the background. This makes it much more challenging to figure out which environmental variables will be kept and which will be changed (when swapping to the root environment). This is not true with sudo -i . Because of this, most people view it as the preferred method to gain root without logging in directly.
In simpler language: sudo -i will give you a “clean” root login in your “/root” folder, which is the “home” folder for the root user.
sudo -s
This command summons a shell with your $SHELL variable.

The -s switch for the sudo command reads the $SHELL variable of the current user executing commands. This command works as if the user is running sudo /bin/bash , if the shell the user comes from is bash.
In our case, sudo -s gave us the fish interactive shell, as we previously installed fish as our default shell, so it would be as if we ran sudo /usr/bin/fish .

Sudo -s is a “non-login” style shell. Unlike a command like sudo -i or sudo su , the system will not read any environmental files. When a user tells the shell to run sudo -s , it gains root but will not change the user environment. Your home will not be the root home, etc.

This command is best used when the user wants to switch over to root but keep the same shell environment. For instance, you may want to run a fish script and not be forced into the default bash shell that root often gets in most distros.
Other commands covered above gain root access but will also give you the shell and environment variables that the distro has for root. Maybe you just want to switch to the user without all that baggage!
Frequently Asked Questions
Why would the shell I'm running with matter?
If you use an unmodified bash shell for your user account, the difference is mostly philosophical. In most instances, elevating to root through either shell will not result in any noticeable change. But if you run anything else, you’ll immediately notice how different things can be!
For example, let’s say you’re running the fish shell for your user account and keep the root shell in bash. Loading the user shell by using sudo -s yields a drastically different result.
The shell will follow whichever configuration you have in root’s home folder. If you don’t have such a thing, it will just load the default configuration instead of your personal one. (In our case, that would be “
/.config/fish/config.fish”.) For all intents and purposes, it’s best to leave things that way rather than copying over the user configuration to “/root”.
Changing to your user account’s shell when swapping over to root should only be done if you need to run a script that absolutely needs that particular shell.
Can accessing root harm my system?
In some cases, yes. Unless you’re absolutely sure you need to access root for everything in a particular terminal session, it’s often better to just type sudo followed by a command, if you want to access root for that particular command. For example, typing sudo apt install vlc in any Debian-based version of Linux would tell the operating system to access root just to run the APT package manager to install VLC.
One very important caveat to running sudo -i or any other variant we’ve discussed earlier as opposed to typing sudo before each command you want to run as root is that the former does not log your command history into “/var/log/auth.log”. If you mess up, you can’t go back and check on what you did so that you can correct it. You’ll have to operate out of memory, as root sessions are not recorded.
When I type "sudo" before a command, which variant of "sudo su" am I running?
By typing sudo to execute a command (i.e., you’re typing it in the same line as the command you want to run), you’re essentially running it under an interactive root shell. This would be what the sudo -s standalone command does. It’s also very similar to running the su -c command.
All screenshots by Miguel Leiva-Gomez.
Miguel has been a business growth and technology expert for more than a decade and has written software for even longer. From his little castle in Romania, he presents cold and analytical perspectives to things that affect the tech world.
Ubuntu. Команды su и sudo
Разделение привилегий — основа безопасности в операционной системе Linux. Обычные пользователи работают с ограниченными привилегиями и могут влиять только на собственную рабочую среду, но не на операционную систему в целом. Пользователь с именем root имеет привилегии суперпользователя — это административная учетная запись без ограничений.
Использование su для получения прав root
Команда su (substitute user) предназначена для замены пользователя. После ввода команды будет предложено ввести пароль root , после чего будет создан сеанс оболочки суперпользователя.
Обратите внимание, что мы не указываем имя пользователя — в этом случае подразумевается, что нужно запустить новый сеанс root . Но можно запустить сеанс от любого пользователя.
Опция -l или —login изменяет контекст выполнения оболочки — переменные $PATH , $HOME , $SHELL , $USER содержат значения, характерные для указанного пользователя.
Справка по команде su .
В Ubuntu для суперпользователя пароль не задан, поэтому нельзя запустить сеанс root . Как правильно ввести пароль, которого нет? Чтобы обойти это ограничение, достаточно добавить sudo перед su .
Хотя в Ubuntu нет пароля для root , его всегда можно установить. И запускать сеанс root с помощью su , без sudo . Но делать это не рекомендуется без веских причин.
Обратите внимание, что мы не указываем имя пользователя для passwd — в этом случае подразумевается root . Чтобы вернуть Ubuntu в исходное состояние, нужно заблокировать учетную запись root .
Использование sudo для запуска команд от root
Команда sudo (substitute user and do) позволяет выполнять разовые команды с привилегиями root без необходимости создавать новую оболочку.
Иногда нужно выполнить несколько команд с правами root и вводить каждый раз sudo (и периодически — пароль) может быть неудобно. Тогда можно начать сеанс root , выполнить все команды, после чего завершить сеанс.
Справка по команде sudo .
Присвоение пользователю привилегий sudo
В Ubuntu группа sudo имеет полные привилегии администратора. Добавляя пользователя в эту группу, мы предоставляем ему такие же привилегии.
Проверка прав при использовании sudo
Проверить, какие права есть у пользователя при использовании команды sudo , можно с помощью опции -l .
Также можно узнать, может ли пользователь с помощью sudo выполнить ту или иную команду. Если команда запрещена, то ничего не будет выведено. Если команда разрешена, то будет выведен полный путь до файла.
Файл конфигурации /etc/sudoers для sudo
Команда sudo настраивается с помощью файла /etc/sudoers . Редактировать это файл можно только с помощью команды visudo , которая перед сохранением проверяет синтаксис файла. Обычно visudo открывает файл /etc/sudoers в текстовом редакторе vi . Однако в Ubuntu команда visudo настроена на использование текстового редактора nano .
Строки по умолчанию Defaults
Первая строка Defaults env_reset сбрасывает среду терминала для удаления переменных пользователя. Эта мера безопасности используется для сброса потенциально опасных переменных среды в сеансе sudo .
Вторая строка, Defaults mail_badpass , предписывает системе отправлять уведомления о неудачных попытках ввода пароля sudo для настроенного пользователя. По умолчанию это учетная запись root .
Третья строка, начинающаяся с Defaults secure_path=… , задает переменную PATH , которая будет использоваться для операций sudo . Это предотвращает использование пользовательских путей, которые могут быть вредоносными.
Бывает, что злоумышленники пытаются запускать вредоносную программу с помощью sudo , которая разветвит фоновый процесс и он остается активным на терминале пользователя, даже после того как основная программа завершила свое выполнение. Чтобы избежать этого, можно настроить sudo на запуск команд только с помощью psuedo-pty с использованием параметра use_pty .
Строки пользовательских привилегий
Пятая строка файла конфигурации определяет права для пользователя root . Давайте посмотрим, что означают различные поля.
Это означает, что пользователь root с помощью sudo может выполнять любые команды от любого пользователя или группы после ввода пароля.
Строки привилегий для групп
Следующие две строки похожи на строки привилегий пользователя, но задают правила sudo для групп. Группа admin может выполнять любые команды от имени любого пользователя на любом хосте. Группа sudo имеет те же привилегии, но может еще выполнять команды от лица любой группы.
Строка @includedir /etc/sudoers.d
Данная строка означает, что файлы в каталоге /etc/sudoers.d также рассматриваются как файлы конфигурации и применяются. В основном это нужно, чтобы приложения могли изменять привилегии sudo после установки. Файлы в этом каталоге следуют тем же правилам, что и сам файл /etc/sudoers . И редактировать эти файлы следует только с помощью команды visudo .
Настройка персонализированных правил
Мы познакомились с общим синтаксисом файла, а теперь попробуем создать новые правила.
Создание псевдонимов
Файл /etc/sudoers можно организовать более эффективно, группируя элементы с помощью разнообразных псевдонимов.
Теперь, имея все необходимые псевдонимы, можно легко задавать — какие пользователи какие команды могут запускать с помощью sudo . От имени кого они будут запускать эти команды и нужно ли при этом вводить пароль.
Если не указать пользователя или группу «запуска от имени», команда sudo по умолчанию использует пользователя root .
Необходимо помнить, что в случае конфликта правил более поздние правила имеют приоритет перед более ранними.
Прочая информация по команде sudo
Если задать в файле конфигурации пользователя или группу, от имени которых выполняются команды, можно выполнять команды от их имени.
Для удобства sudo сохраняет данные аутентификации в течение определенного количества времени на одном терминале. Это означает, что не нужно будет вводить пароль снова, пока это время не истечет. В Ubuntu по умолчанию это 15 минут — изменить это можно, если добавить следующую строку в файл конфигурации.
Если указать ноль — пароль будет запрашиваться каждый раз при использовании sudo . Если указать отрицательное значение — пароль не будет запрашиваться до следующей перезагрузки системы.
Команда sudo -k позволяет сбросить таймер сохранения данных аутентификации. То есть, после выполнения команды с использованием sudo , выполнение команды sudo -k удалит данные аутентификации.
Команда sudo -v запросит пароль и сохранит данные аутентификации для последующего использования sudo без ввода пароля. Данные аутентификации сохраняются на то кол-во минут, которое указано в файле конфигурации.