Как запустить программу от имени другого пользователя linux
Перейти к содержимому

Как запустить программу от имени другого пользователя linux

  • автор:

Как запустить программу от имени другого пользователя linux

Sudo allows a system administrator to delegate authority to give certain users—or groups of users—the ability to run commands as root or another user while providing an audit trail of the commands and their arguments.

Sudo is an alternative to su for running commands as root. Unlike su, which launches a root shell that allows all further commands root access, sudo instead grants temporary privilege elevation to a single command. By enabling root privileges only when needed, sudo usage reduces the likelihood that a typo or a bug in an invoked command will ruin the system.

Sudo can also be used to run commands as other users; additionally, sudo logs all commands and failed access attempts for security auditing.

Installation

Usage

To begin using sudo as a non-privileged user, it must be properly configured. See #Configuration.

To use sudo, simply prefix a command and its arguments with sudo and a space:

For example, to use pacman:

See sudo(8) for more information.

Configuration

alt=»Tango-view-fullscreen.png» width=»48″ height=»48″ />This article or section needs expansion. alt=»Tango-view-fullscreen.png» width=»48″ height=»48″ />

Defaults skeleton

sudoers(5) § SUDOERS OPTIONS lists all the options that can be used with the Defaults command in the /etc/sudoers file.

See [1] for a list of options (parsed from the version 1.8.7 source code) in a format optimized for sudoers .

See sudoers(5) for more information, such as configuring the password timeout.

View current settings

Run sudo -ll to print out the current sudo configuration, or sudo -lU user for a specific user.

Using visudo

The configuration file for sudo is /etc/sudoers . It should always be edited with the visudo(8) command. visudo locks the sudoers file, saves edits to a temporary file, and checks it for syntax errors before copying it to /etc/sudoers .

  • It is imperative that sudoers be free of syntax errors! Any error makes sudo unusable. Always edit it with visudo to prevent errors.
  • visudo(8) warns that configuring visudo to honor the user environment variables for their editor of choice may be a security hole, since it allows the user with visudo privileges to run arbitrary commands as root without logging simply by setting that variable to something else.

The default editor for visudo is vi. The sudo package is compiled with —with-env-editor and honors the use of the SUDO_EDITOR , VISUAL and EDITOR variables. EDITOR is not used when VISUAL is set.

To establish nano as the visudo editor for the duration of the current shell session, export EDITOR=nano ; to use a different editor just once simply set the variable before calling visudo:

Alternatively you may edit a copy of the /etc/sudoers file and check it using visudo -c /copy/of/sudoers . This might come in handy in case you want to circumvent locking the file with visudo.

To change the editor permanently, see Environment variables#Per user. To change the editor of choice permanently system-wide only for visudo, add the following to /etc/sudoers (assuming nano is your preferred editor):

Example entries

To allow a user to gain full root privileges when they precede a command with sudo , add the following line:

To allow a user to run all commands as any user but only on the machine with hostname HOST_NAME :

To allow members of group wheel sudo access:

To disable asking for a password for user USER_NAME :

Enable explicitly defined commands only for user USER_NAME on host HOST_NAME :

Enable explicitly defined commands only for user USER_NAME on host HOST_NAME without password:

A detailed sudoers example is available at /usr/share/doc/sudo/examples/sudoers . Otherwise, see the sudoers(5) for detailed information.

Sudoers default file permissions

The owner and group for the sudoers file must both be 0. The file permissions must be set to 0440. These permissions are set by default, but if you accidentally change them, they should be changed back immediately or sudo will fail.

Tips and tricks

Disable password prompt timeout

A common annoyance is a long-running process that runs on a background terminal somewhere that runs with normal permissions and elevates only when needed. This leads to a sudo password prompt which goes unnoticed and times out, at which point the process dies and the work done is lost or, at best, cached. Common advice is to enable passwordless sudo, or extend the timeout of sudo remembering a password. Both of these have negative security implications. The prompt timeout can also be disabled and since that does not serve any reasonable security purpose it should be the solution here:

Add terminal bell to the password prompt

To draw attention to a sudo prompt in a background terminal, users can simply make it echo a bell character:

Note the ^G is a literal bell character. E.g. in vim, insert using the sequence Ctrl+v Ctrl+g . If Ctrl+v is mapped, e.g. for pasting, one can usually use Ctrl+q instead. In nano, Alt+v Ctrl+g .

alt=»Tango-view-fullscreen.png» width=»48″ height=»48″ />This article or section needs expansion. alt=»Tango-view-fullscreen.png» width=»48″ height=»48″ />

Another option is to set the SUDO_PROMPT environment variable. For example, add the following to your shell configuration file:

Passing aliases

Aliases in Zsh and Bash are normally only expanded for the first word in a command. This means that your aliases will not normally get expanded when running the sudo command. One way to make the next word expand is to make an alias for sudo ending with a space. Add the following to your shell’s configuration file:

If the replacement text ends with a space, the next word in the shell input is always eligible for purposes of alias expansions.

If the last character of the alias value is a blank, then the next command word following the alias is also checked for alias expansion.

Disable per-terminal sudo

If you are annoyed by sudo’s defaults that require you to enter your password every time you open a new terminal, set timestamp_type to global :

Reduce the number of times you have to type a password

If you are annoyed that you have to re-enter your password every 5 minutes (default), you can change this by setting a longer value for timestamp_timeout (in minutes):

If you are using a lot of sudo commands on a row, it is more logical to refresh the timeout every time you use sudo than to increase timestamp_timeout . Refreshing the timeout can be done with sudo -v (whereas sudo -K revokes immediately).

You might want to automate this by adding the following to your shell initialization files:

It is also possible to use a bash function; for more details see stackexchange.

Environment variables

If you have a lot of environment variables, or you export your proxy settings via export http_proxy=». » , when using sudo these variables do not get passed to the root account unless you run sudo with the -E / —preserve-env option.

The recommended way of preserving environment variables is to append them to env_keep :

Root password

Users can configure sudo to ask for the root password instead of the user password by adding targetpw (target user, defaults to root) or rootpw to the Defaults line in /etc/sudoers :

To prevent exposing your root password to users, you can restrict this to a specific group:

Disable root login

Users may wish to disable the root login. Without root, attackers must first guess a user name configured as a sudoer as well as the user password. See for example OpenSSH#Deny.

  • Be careful, you may lock yourself out by disabling root login. Sudo is not automatically installed and its default configuration allows neither passwordless root access nor root access with your own password. Ensure a user is properly configured as a sudoer before disabling the root account!
  • If you have changed your sudoers file to use rootpw as default, then do not disable root login with any of the following commands!
  • If you are already locked out, see Password recovery for help.

The account can be locked via passwd :

A similar command unlocks root.

Alternatively, edit /etc/shadow and replace the root’s encrypted password with «!»:

To enable root login again:

kdesu

kdesu may be used under KDE to launch GUI applications with root privileges. It is possible that by default kdesu will try to use su even if the root account is disabled. Fortunately one can tell kdesu to use sudo instead of su. Create/edit the file

or use the following command:

Harden with sudo example

Let us say you create 3 users: admin, devel, and archie. The user «admin» is used for journalctl, systemctl, mount, kill, and iptables; «devel» is used for installing packages, and editing configuration files; and «archie» is the user you log in with. To let «archie» reboot, shutdown, and use netctl we would do the following:

Edit /etc/pam.d/su and /etc/pam.d/su-l . Require user be in the wheel group, but do not put anyone in it.

Limit SSH login to the ‘ssh’ group. Only «archie» will be part of this group.

Add users to other groups.

Set permissions on configs so devel can edit them.

With this setup, you will almost never need to login as the root user.

«archie» can connect to their home WiFi.

«archie» can not use netctl as any other user.

When «archie» needs to use journalctl or kill run away process they can switch to that user.

But «archie» cannot switch to the root user.

If «archie» want to start a gnu-screen session as admin they can do it like this:

Configure sudo using drop-in files in /etc/sudoers.d

sudo parses files contained in the directory /etc/sudoers.d/ . This means that instead of editing /etc/sudoers , you can change settings in standalone files and drop them in that directory. This has two advantages:

  • There is no need to edit a sudoers.pacnew file;
  • If there is a problem with a new entry, you can remove the offending file instead of editing /etc/sudoers (but see the warning below).

The format for entries in these drop-in files is the same as for /etc/sudoers itself. To edit them directly, use visudo -f /etc/sudoers.d/somefile . See sudoers(5) § Including other files from within sudoers for details.

The files in /etc/sudoers.d/ directory are parsed in lexicographical order, file names containing . or

are skipped. To avoid sorting problems, the file names should begin with two digits, e.g. 01_foo .

Editing files

sudo provides the sudoedit command (equivalent to sudo -e ). This is useful for editing files which can be edited by root only while still running the editor as a normal user, and using that user’s configuration.

To edit a file, set SUDO_EDITOR to the name of the editor and pass the file name to sudoedit . For example:

If multiple names are passed to sudo , all files are opened in the editor in a single invocation. A feature useful for merging files:

Enable insults

Users can enable the insults easter egg in sudo by adding the following line in the sudoers file with visudo .

Upon entering an incorrect password this will replace Sorry, try again. message with humorous insults.

Enable password input feedback

By default, there is no visual feedback when you input a password. That is done on purpose for extra security. However, if you wish to have visual input, you can enable it by adding this line:

Colored password prompt

To customize the password prompt with colors and/or bold fonts, set the SUDO_PROMPT environment variable in your shell initialization file and use tput(1) .

For example, to set the password prompt to display Password: in bold red, use this:

Or use different colors with the default message like so:

alt=»Merge-arrows-2.png» width=»48″ height=»48″ />This article or section is a candidate for merging with Color output in console. alt=»Merge-arrows-2.png» width=»48″ height=»48″ />

tput command line option cheatsheet

tput command Description
tput bold Bold text
tput setaf [CODE] Set foreground color
tput setab [CODE] Set background color
tput rev Inverse colors
tput sgr0 Reset everything

Troubleshooting

SSH problem without TTY

alt=»Merge-arrows-2.png» width=»48″ height=»48″ />This article or section is a candidate for merging with #Configuration. alt=»Merge-arrows-2.png» width=»48″ height=»48″ />

SSH does not allocate a tty by default when running a remote command. Without an allocated tty, sudo cannot prevent the password from being displayed. You can use ssh’s -t option to force it to allocate a tty.

The Defaults option requiretty only allows the user to run sudo if they have a tty.

Permissive umask

alt=»Merge-arrows-2.png» width=»48″ height=»48″ />This article or section is a candidate for merging with #Configuration. alt=»Merge-arrows-2.png» width=»48″ height=»48″ />

Sudo will union the user’s umask value with its own umask (which defaults to 0022). This prevents sudo from creating files with more open permissions than the user’s umask allows. While this is a sane default if no custom umask is in use, this can lead to situations where a utility run by sudo may create files with different permissions than if run by root directly. If errors arise from this, sudo provides a means to fix the umask, even if the desired umask is more permissive than the umask that the user has specified. Adding this (using visudo ) will override sudo’s default behavior:

This sets sudo’s umask to root’s default umask (0022) and overrides the default behavior, always using the indicated umask regardless of what umask the user as set.

Запустить команду от другого пользователя в Unix/Linux

Запустить команду от другого пользователя в Unix/Linux

Иногда, просто необходимо запустить команду от другого пользователя. И существует несколько способов, как это можно сделать. Я расскажу о них в своей статья «Запустить команду от другого пользователя в Unix/Linux».

Запустить команду от другого пользователя в Unix/Linux — способ 1

И так, можно использовать утилиту SUDO. Рассмотрим пример:

  • -H YOUR_HOME: Задает HOME (Переменное окружение для хома конкретного юзера) и по умолчанию — это root.
  • -u YOUR_USER: Задаем пользователя от которого будет выполнена команда.
  • -c YOUR_COMMAND: Служит опцией для ввода команды.

Запустить команду от другого пользователя в Unix/Linux — способ 2

Можно использовать утилиту SU. И сейчас приведу несколько примеров.

Логин в root юзера

Чтобы получить рута, выполните:

Запустить команду как root юзер

Вот пример команды:

Выполнить команду от другого пользователя с помощью su

И так, вот пример:

Рассмотрим другой пример:

  • — — Будет имитировать логин указанного пользователя.
  • -c — Служит для указания команды для выполнения (для указанного юзверя).

Запустить команду от другого пользователя в Unix/Linux — способ 3

И так, можно использовать утилиту runuser. Команда runuser запускает оболочку с заменяющими идентификаторами пользователей и групп. Эта команда полезна только когда вы залогинены как пользователь root. Синтаксис выглядит следующим образом:

Как пример, я покажу следующую строку:

PS: Для использования команды runuser пароль не требуется, и он должен запускаться только пользователем root.

  • -l: Создаст оболочку для входа в систему, используя файл runuser-l PAM вместо стандартного.
  • -g: Указывает на основную группу.
  • -G: Указывает на дополнительную группу.
  • -c: Собственно, служит для указания команды.
  • –session-command=COMMAND: Передает одну команду в оболочку с опцией «-c» и не создает новый сеанс.
  • -m: Не сбрасывайте переменные среды (ENV).

Вот и все, тема «Запустить команду от другого пользователя в Unix/Linux» завершена.

Как выполнить программу от имени другого пользователя?

В системе несколько пользователей. Захожу на сервер через ssh от имени root.

Вопрос: как запустить скрипт:

от имени пользователя user, залогинившись под пользователем root?

aleksandr barakin's user avatar

выполнить программу (с опциями/параметрами или без них) от имени указанного пользователя можно:

с помощью программы su (присутствует в системе обязательно):

кавычки — обязательны; одинарные или двойные — в данном случае роли не играет.

с помощью программы sudo (если установлена):

здесь программа [опции|параметры] — это (для приведённого в вопросе примера) php /пусть_до_файла/1.php

если программа su или sudo выполняется от имени пользователя с идентификатором 0 (обычно он имеет имя root ), то пароль не запрашивается. о разнице между этими программами: В чём разница между su и sudo?

Команды su и sudo в Linux. В чем разница?

С командами su и sudo сталкивается каждый пользователь Linux. При этом, поскольку они имеют схожий синтаксис и выполняют практически одну и ту же задачу, многие новички не понимают, в каких случаях следует использовать ту или иную команду. На этом уроке мы узнаем, чем отличается su от sudo.

su против sudo

root или суперпользователь — это специальный аккаунт и группа пользователей в Unix-подобных системах с идентификатором, владелец которого имеет право на выполнение всех без исключения операций.

su и sudo — это два разных способа получить привилегии суперпользователя (root), обладающего максимальными правами и возможностью делать с системой всё, что угодно. В Windows такая учетная запись носит название «Администратор». Обычные (непривилегированные) пользователи в Linux сильно ограничены в таких правах: у них нет возможности производить запись в системные каталоги, управлять системными процессами и т.п. Поэтому для выполнения чего-то, что требует повышенных привилегий, и применяются команды su и sudo.

Основное различие между ними заключается в том, что su требует пароль целевой учетной записи (например, пользователя root) и переключает вас на нее, в то время как sudo требует пароль текущего пользователя и запускает от его имени только лишь одну (или несколько) команд, на выполнение которых требуются права пользователя root. Поэтому гораздо безопаснее использовать sudo, поскольку применение данной команды не включает в себя обмен конфиденциальной информацией.

Кроме того, рекомендуется отдавать предпочтение sudo при выполнении задач, требующих root-привилегий. В этом случае текущему пользователю предоставляются привилегии исключительно для указанной команды. С другой стороны, su полностью переключается на пользователя root, подвергая всю систему риску непреднамеренно изменить или удалить какой-нибудь жизненно-важный компонент.

Команда su

Команда su (от англ. «substitute user»«заменить пользователя») применяется в основном для переключения с одного пользователя на другого. При этом она может, как запустить оболочку входа в условиях текущего каталога и окружения ( su ), так и полностью изменить настройки, заменив их окружением целевого пользователя ( su — ).

Если использовать данную команду без [имя_пользователя] , то она переключит вас на учетную запись суперпользователя (root).

Примечание: В большинстве случаев, команда su (с дефисом и без) используется только для переключения на суперпользователя (root), хотя она может переключить вас и на другого ( [имя_пользователя] ) пользователя.

Как работает команда su?

Чтобы вызвать оболочку другого пользователя с окружением и рабочим каталогом текущего пользователя, используйте команду su (без дефиса). Например, если вы хотите работать от имени пользователя ravesli, выполните:

Затем введите пароль для учетной записи ravesli и нажмите Enter.

Оболочка должна измениться, и теперь у вас есть доступ к указанной учетной записи. Однако пользовательское окружение осталось старым:

Как работает команда su –?

Чтобы перейти к другому пользователю и при этом изменить и пользовательское окружение, используйте команду su — :

Примечание: Еще один способ, позволяющий получить доступ к аккаунту другого пользователя вместе с полным объемом переменных его пользовательского окружения, это задействовать команду su -l (или —login ) [имя_пользователя] .

Команда sudo

Команда sudo (от англ. «Substitute User and do««подменить пользователя и выполнить») используется в качестве префикса к командам Linux, позволяя вошедшему в систему пользователю выполнять команды, требующие привилегий root. В отличие от su, команда sudo требует ввода пароля текущего пользователя (выполняющего эту команду).

Например, все исполняемые и административные задачи требуют наличия максимальных разрешений (root). В таких случаях рекомендуется использовать sudo:

Прежде чем система выполнит команду, она запросит пароль текущего пользователя. Имейте в виду, что sudo может применяться только пользователями, принадлежащими к группе sudoers.

Добавление пользователя в группу sudoers

Чтобы пользователь мог выполнить команду, для которой требуется sudo, ему необходимо быть частью группы sudoers. Для добавления пользователя в группу sudoers, выполните следующую команду (от имени root или учетной записи, которая может применять sudo):

usermod -aG sudo [имя_пользователя]

Например, чтобы добавить в группу sudoers учетную запись ravesli, вы должны ввести:

sudo usermod -aG sudo ravesli

Чтобы просмотреть список учетных записей, принадлежащих группе sudoers, выполните:

sudo getent group sudo

Вывод отобразит учетную запись, добавленную на предыдущем шаге:

Еще один способ добавления пользователя в группу sudoers — это воспользоваться командой visudo, которая помогает отредактировать файл /etc/sudoers. Для этого выполните вход в учетную запись root (команда su — ), после чего вызовите visudo и добавьте в файл следующую строку, заменив user на нужное вам имя пользователя, которому вы хотите дать доступ к sudo:

user ALL=(ALL:ALL) ALL

Нажмите Ctrl+X, а затем Y, чтобы сохранить файл. Вы также можете добавить пользователя в группу, указанную в файле /etc/sudoers. Пользователи групп, указанных в данном файле, автоматически получат привилегии sudo.

su и sudo в разных дистрибутивах Linux

su — это традиционный (более старый) способ переключения на учетную запись root (и получение повышенных прав) в Linux.

Сообщество разработчиков Linux не рекомендует на постоянной основе работать под учетной записью пользователя root, поскольку это может привести к нежелательным изменениям в системе, и предлагает вместо этого применять sudo. По этой причине, во всех производных от Ubuntu дистрибутивах Linux учетная запись root по умолчанию отключена. Вместо нее предлагается использовать sudo.

При установке, например, дистрибутива Linux Mint, вы автоматически создаете пользователя, помеченного как член группы sudoers. При этом настройки учетной записи root не предполагается. Чтобы включить пользователя root, вам необходимо активировать его вручную.

С другой стороны, другие дистрибутивы Linux, такие как Fedora, при установке создают обе учетные записи: обычного пользователя и суперпользователя (root).

Включение учетной записи root

Если вы используете Ubuntu-подобный дистрибутив (например, вышеупомянутый Linux Mint) и попытаетесь переключиться на пользователя root, то получите сообщение о сбое аутентификации:

Чтобы активировать пользователя root, выполните команду passwd :

sudo passwd root

Затем установите пароль и нажмите Enter. В результате система должна уведомить вас, что пароль пользователя root был успешно обновлен:

Убеждаемся, что пользователь root активирован, переключившись на него с помощью команды su — :

Заключение

Не забывайте использовать sudo всякий раз, когда это возможно. Благодаря этому вы снизите риск привести вашу систему в нерабочее состояние, а также повысите её защищенность от различных угроз безопасности.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *