Linux what is sudo access

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.

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 :

Источник

Linux 101: Introduction to sudo

There are two ways to run administrative applications in Linux. You can either switch to the super user (root) with the su command, or you can take advantage of sudo. How you do this will depend upon which distribution you use. Some distributions enable the root user (such as Fedora, Red Hat, openSuSE), while some do not (such as Ubuntu and Debian). There are pros and cons for each.

Sudo stands for either “substitute user do” or “super user do” (depending upon how you want to look at it). What sudo does is incredibly important and crucial to many Linux distributions. Effectively, sudo allows a user to run a program as another user (most often the root user). There are many that think sudo is the best way to achieve “best practice security” on Linux. There are some, however, that feel quite the opposite. Regardless of where you stand, and what distribution you are currently using, there will come a time when you will have to take advantage of sudo. Whether you will need to simply use sudo or you will have to configure sudo you will want to know the ins and outs of this powerful tool.

In this article I am going to introduce you to sudo…a little history, a little use, and a little configuration. In the end you should feel as at home with sudo as you do with su.

Читайте также:  How run python script linux

History of sudo

Sudo found its beginnings in 1980 at the department of computer science SUNY/Buffalo (created by Bob Coggeshall and Cliff Spencer). Since it’s first inception, sudo has been re-iterated numerous time (adding new features and changing developers). At one point, around 1994, sudo was being developed by Todd Miller at the Colorado University in Boulder, CO and an unofficial “fork” of sudo was released called “CU sudo”. This “fork” added support for more distributions as well as numerous bug fixes. This “CU” prefix was finally dropped in 1999 and what was “CU sudo” is now the version of sudo we use today. The original sudo has not had a release since 1991. So the “fork” won and is still developed by Todd Miller.

Now that you have had a bit of a history lesson, let’s take a look and see how sudo is used.

Difference Between sudo and su

If you are accustomed to a more traditional Linux setup, then you are used to using the su command to gain root privileges. You can even issue the command su – to effectively log in as the root (root’s home becomes your home). With these types of distributions you can also log in as the root user. To many (including myself) this is a bad idea. NEVER log in as the root user. If you are using a distribution that relies on su and allows root user log in, log in as your standard user and su to the root user.

Now with sudo-based distributions you will most likely notice that you can not log in as a root user. In fact, in distributions such as Ubuntu, the root user account has been “disabled.” You cannot log in as root and you cannot su to become the root user. All you can do is issue commands with the help of sudo to gain administrative privileges.

Usage

Using sudo, in its most basic form, is simple. Say you have to run the dpkg to install a piece of software. If, as your standard user, you just issue the command dpkg -i software.deb you will receive an error warning you that the user does not have proper permissions to execute the command. That is because standard users, by default, cannot install applications on a Linux machine. In order to successfully install an application on a Linux machine you have to have super user privileges. So, to change that command so that you can successfully run the installation, you would instead issue the command sudo dpkg -i software.deb.

Configuration

Now let’s take a look at the configuration of sudo. I will give you a word of warning: If you mis-configure your /etc/sudoers file, you can damage your installation (at which point you will have to log boot in rescue mode). Sudo is VERY particular about syntax in the configuration file. So always double check your configurations before you save your file. Fortunately there is only one file you need to concern yourself with and that is /etc/sudoers. You may notice that, even in order to view the /etc/sudoers file you have to use the sudo command. This file will seem very simple…it is once you understand the layout and the function.

To make changes to the sudo configuration file you need to use a specific command – sudo visudo. When you open up this file you will notice that the sudoers file is fairly small in size. There really isn’t much to it, but what there is to it is key. Let’s take a look at how to add a user to the sudoers file.

The basic entry for a user looks like this:

user hostlist = (userlist) commandlist

Typically you will find an entry like this:

Which indicates that the user root on all hosts using any user can run all commands. Fairly straight-forward. But let’s say you want to allow a single user access to one administrative command without having to enter a password. Let’s use the command dpkg (not wise, but an easy means of illustration) and allow the user mary to issue those commands without having to issue a password. To do this you would add a line similar to this:

mary ALL = NOPASSWD: /usr/sbin/synaptic

to the /etc/sudoers file. Now the user mary can run synaptic by entering sudo synaptic but will not be prompted for a password. This is handy on a single-user system but should be used with caution. You do not want to allow just any command to be run sans password or you open yourself to all sorts of vulnerabilities.

Now, let’s say you want to prevent certain users from using sudo. You can do this as well. If you have one user that is to be administrator of a machine, say bethany, and all other users should be uses without admin privileges, you can do this a couple of ways. The first (and less desirable method) is to do the following:

Читайте также:  Microsoft bluetooth stacks windows 10

Add an entry for bethany like so:

bethany ALL=(ALL) ALL

And now comment out the entry:

by adding a “#” character at the beginning of the line.

At this point the only user on the system that will be able to run administrative commands is bethany. Now this can cause issues if you have certain applications that must run with administrative privileges and are allowed such privileges by being a member of the admin group. You can avoid this issue by simply opening up the Users administrative tool and removing all users, except for those you want to be allowed to have admin rights from the admin group. Let’s stick with our example. You want all users other than bethany to have restricted access to run administrative commands and tools. To do this, follow these steps:

Open up the User administrator.

Go to the Groups manager.

Select the admin group.

Uncheck all users but bethany from the list.

Close the Groups manager and the User administrator.

Now only the user bethany will have administrative rights on the machine.

Final Thoughts

Although this has mostly been an introductory look at sudo, you should have a firm grasp on how this tool works and how powerful it is. For further reading on sudo, issue the command man sudo, which will open up the manual page for the sudo command. Just remember, use caution when editing your /etc/sudoers file or you can wind up having to reboot in rescue mode to save your system.

Источник

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.

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, но начнем с её синтаксиса.

Читайте также:  Windows скриншот по сети

Синтаксис 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:

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

Источник

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