- Linux Run Command As Another User
- 1. Using Linux runuser command as another user
- The runuser command options
- 2. Run a Linux command with substitute user and group ID using ‘su command’
- How do I run a command as the system administrator (root)
- 4 Answers 4
- Running a shell command as root
- sudo (preferred when not running a graphical display)
- Logging in as root
- Single User Mode
- Other programs
- Calife
- Super
- Running a graphical command as root
- PolicyKit (preferred when using GNOME)
- KdeSu, KdeSudo (preferred when using KDE)
- Other programs
- Obsolete methods
- Manually via one of the shell-based methods
- Editing a file as root
- How to run applications as root?
- 4 Answers 4
- Администратор в Ubuntu, или Что такое sudo
- Содержание
- Что такое sudo
- Где используется sudo
- Запуск графических программ с правами администратора
- Запуск программ с правами администратора в терминале
- Получение прав суперпользователя для выполнения нескольких команд
- Использование традиционного root аккаунта и команды su
- Ubuntu 11.04 и младше
- Ubuntu 11.10 и старше
- Настройка sudo и прав доступа на выполнение различных команд
- Разрешение пользователю выполнять команду без ввода пароля
- Создание синонимов (alias`ов)
- Время действия введённого пароля
- sudo не спрашивает пароль
Linux Run Command As Another User
Dear nixCraft,
I just want to know how to run Linux commands as another user or as the root user?
–Sincerely,
Confused About Linux commands.
Dear Confused,
You can use the following commands to run as another user or as root user on Linux.
1. Using Linux runuser command as another user
Only session PAM hooks are run, and there is no password prompt. If run as a non-root user without privilege to set user ID, the command will fail as the binary is not setuid. As runuser doesn’t run auth and account PAM hooks, it runs with lower overhead than su.
For example, as a root user you may want to check shell resource limits for oracle user, enter:
# runuser -l oracle -c ‘ulimit -SHa’
Check nginx or lighttpd web server limitations:
# runuser -l nginx -c ‘ulimit -SHa’
# runuser -l lighttpd -c ‘ulimit -SHa’
Sometime, a root user can not browse NFS mounted share due to permission (security) issue:
# ls -l /nfs/wwwroot/cyberciti.biz/http
OR
# cd /nfs/wwwroot/cyberciti.biz/http
Sample outputs:
However, apache user is allowed to browse or access nfs based system mouted at /nfs/wwwroot/cyberciti.biz/http/:
# runuser -l apache -c ‘ls -l /nfs/wwwroot/cyberciti.biz/http/’
# runuser -l apache -c ‘cd /nfs/wwwroot/cyberciti.biz/http/; vi index.php’
No password is required to use runuser command and it must be run by root user only. Sometimes sudo or su will give following error:
To get around this try the following syntax:
# runuser -u www-data — command
## Run commands as www-data user ##
# runuser -u www-data — composer update —no-dev
# runuser -u www-data — php7 /app/maintenance/update.php
The runuser command options
- -l user_login_name : Make the shell a login shell, uses runuser-l PAM file instead of default one.
- -g group : Specify the primary group.
- -G group : Specify a supplemental group.
- -c COMMAND : Pass a single COMMAND to the shell with -c.
- —session-command=COMMAND : Pass a single COMMAND to the shell with -c and do not create a new session.
- -m : Do not reset environment variables.
- -u username : Run command as given username to get around ‘su -‘ or ‘sudo’ limit.
2. Run a Linux command with substitute user and group ID using ‘su command’
The su command allows you to become a super user or substitute user, spoof user, set user or switch user. It allows a Linux user to change the current user account associated with the running console or shell provided that you know the target user’s password. The syntax is as follows:
Источник
How do I run a command as the system administrator (root)
I need to run a command with administrative privileges. Someone said I should run a command as root. How do I do this?
4 Answers 4
The main two commandline possibilities are:
- Use su and enter the root password when prompted.
- Put sudo in front of the command, and enter your password when prompted.
Running a shell command as root
sudo (preferred when not running a graphical display)
This is the preferred method on most systems, including Ubuntu, Linux Mint, (arguably) Debian, and others. If you don’t know a separate root password, use this method.
Sudo requires that you type your own password. (The purpose is to limit the damage if you leave your keyboard unattended and unlocked, and also to ensure that you really wish to run that command and it wasn’t e.g. a typo.) It is often configured to not ask again for a few minutes so you can run several sudo commands in succession.
If you need to run several commands as root, prefix each of them with sudo . Sometimes, it is more convenient to run an interactive shell as root. You can use sudo -i for that:
Instead of sudo -i , you can use sudo -s . The difference is that -i reinitializes the environment to sane defaults, whereas -s uses your configuration files for better or for worse.
For more information, see the sudo website, or type man sudo on your system. Sudo is very configurable; for example it can be configured to let a certain user only execute certain commands as root. Read the sudoers man page for more information; use sudo visudo to edit the sudoers file.
The su command exists on most unix-like systems. It lets you run a command as another user, provided you know that user’s password. When run with no user specified, su will default to the root account.
The command to run must be passed using the -c option. Note that you need quotes so that the command is not parsed by your shell, but passed intact to the root shell that su runs.
To run multiple commands as root, it is more convenient to start an interactive shell.
On some systems, you need to be in group number 0 (called wheel ) to use su . (The point is to limit the damage if the root password is accidentally leaked to someone.)
Logging in as root
If there is a root password set and you are in possession of it, you can simply type root at the login prompt and enter the root password. Be very careful, and avoid running complex applications as root as they might do something you didn’t intend. Logging in directly as root is mainly useful in emergency situations, such as disk failures or when you’ve locked yourself out of your account.
Single User Mode
Single user mode, or run-level 1, also gives you root privileges. This is intended primarily for emergency maintenance situations where booting into a multi-user run-level is not possible. You can boot into single user mode by passing single or emergency on the kernel command line. Note that booting into single-user mode is not the same as booting the system normally and logging in as root. Rather, the system will only start the services defined for run-level 1. Typically, this is the smallest number of services required to have a usable system.
You can also get to single user mode by using the telinit command: telinit 1 ; however, this command requires you to already have gotten root privileges via some other method in order to run.
On many systems booting into single user mode will give the user access to a root shell without prompting for a password. Notably, systemd -based systems will prompt you for the root password when you boot this way.
Other programs
Calife
Calife lets you run commands as another user by typing your own password, if authorized. It is similar to the much more widespread sudo (see above). Calife is more light-weight than sudo but also less configurable.
Op lets you run commands as another user, including root. This not a full-blown tool to run arbitrary commands: you type op followed by a mnemonic configured by the system administrator to run a specific command.
Super
Super lets you run commands as another user, including root. The command must have been allowed by the system administrator.
Running a graphical command as root
PolicyKit (preferred when using GNOME)
Simply prefix your desired command with the command pkexec . Be aware that while this works in most cases, it does not work universally.
See man pkexec for more information.
KdeSu, KdeSudo (preferred when using KDE)
kdesu and kdesudo are graphical front-ends to su and sudo respectively. They allow you to run X Window programs as root with no hassle. They are part of KDE. Type
and enter the root password, or type
and enter your password (if authorized to run sudo ). If you check the “keep password” option in KdeSu, you will only have to type the root password once per login session.
Other programs
Ktsuss (“keep the su simple, stupid”) is a graphical version of su.
Beesu is a graphical front-end to the su command that has replaced Gksu in Red Hat-based operating systems. It has been developed mainly for RHEL and Fedora.
Obsolete methods
gksu and gksudo are graphical front-ends to su and sudo respectively. They allow you to run X Window programs as root with no hassle. They are part of Gnome. Type
and enter the root password, or type
and enter your password (if authorized to run sudo ).
gksu and gksudo are obsolete. They have been replaced by PolicyKit in GNOME, and many distributions (such as Ubuntu) no longer install them by default. You should not depend on them being available or working properly.
Manually via one of the shell-based methods
Use one of the methods in the «running a shell command as root section». You will need to ensure that neither the DISPLAY environment variable nor the XAUTHORITY environment get reset during the transition to root. This may require additional configuration of those methods that is outside the scope of this question.
Overall, this is a bad idea, mostly because graphical applications will read and write configuration files as root, and when you try to use those applications again as your normal user, those applications won’t have permission to read their own configurations.
Editing a file as root
In either case, you will be prompted for the root password. For more information, see the manual page.
Since the question was not Linux specific, here’s how you achieve the same goal in Solaris 9+ (or Trusted Solaris 8):
Solaris, since version 9, has included a suite of tools affectionately referred to as RBAC, or Role Based Access Control.
The gist of RBAC is that through the granting of Authorizations and Rights, to Users and/or Role, or the granting of Roles to Users, you can create incredibly fine grained models for who can run what with which privileges.
Essentially, you identify authorization in /etc/security/auth_attr, then grant them to users or roles in /etc/user_attr.
You define profiles in /etc/security/prof_attr. You then associate commands with those profiles in /etc/security/exec_attr, followed by assigning those profiles to users in the /etc/user_attr file.
Once those things are done, you actually run pfexec to execute the command with privileged or authorizations that are granted to that user for that command.
The nice thing about RBAC is that there are no additional privileges granted to the command itself, or the user, only to the combination of user + command. So it’s safer than making a binary +s, or just using sudo to make a user be able to execute pretty much anything. (I know that you can lock down sudo, but in my experience most people don’t)
Another advantage of RBAC is that you can make root a role account, and assign that role to users who are able to become root with the ‘su’ command and the root password. The root user will also be able to log in in Single User Mode, which is better (in my opinion) than the Linux model where you can disable the root password passwd -d root , or lock the root account passwd -l root , both of which make logging in as root quite hard when something goes wrong.
Ben Rockwood has a great blog post on RBAC that can be read at Using RBAC on (Open)Solaris.
Источник
How to run applications as root?
I am having some strange issue with Kate and Kwrite. When I click on Open File, it crashes with segmentation fault.
I am a complete newbie to Linux, and I think the issue is that I am not running the application as root.
How do I run applications as root in Ubuntu? Is it bad practice to do this? What is the purpose of the whole root thing, where even though we need to use root so frequently, it is not utilized as default?
4 Answers 4
It is pretty simple to run a program as root.
For a console program use
If it is a GUI application use
UNIX-like operating systems (including Linux) use a concept called privilege separation to ensure that the system stays safe. UNIX was designed as a multi-user system from the ground up — that is, it was designed so that many people could use one computer running UNIX at once. Because most users don’t need to be able to modify the core system only the system administrator should have that privilege. That privileged user is traditionally called root. (Root is a lot like Administrator in Windows.)
This makes sense on several levels. Commonly, a web server or other process that exposes a port to other (possibly malicious) computers will run as its own user (Apache runs as the user nobody ), so that even if the web server program is hacked, the attacker can’t trash the entire machine quite so easily. It even makes sense for mostly single-user machines such as desktops: if other members of your family, for example, somehow manage to run rm -rf / (do NOT run that), they won’t have permission to delete every file on the system, like they would if there were no such thing as privilege separation.
There are several commands you can use to elevate your privileges. The sudo command exists to temporarily give you root-level privileges when you need them to administer the system. You can also use the commands gksudo or su . The latter can be used only if you know root’s password and is a good option if your account doesn’t have permission to use sudo .
The root user can do anything on a system, with almost no exceptions. So even if you request something by accident, it will be carried out with little or no warning, even if it’s bad for the health of your system. This is why it’s good practice to do most of your activities as a normal user, and use root only when needed, like when you’re installing a program.
You shouldn’t need to use root to get rid of a segmentation fault. If root is the only thing that fixes a segfault, then the program has a bug. Programs should not fail like that just because they don’t have root.
Источник
Администратор в Ubuntu, или Что такое sudo
Содержание
В любой Linux-системе обязательно есть один привилегированный пользователь — root. Этот пользователь имеет права на выполнение любых действий, удаление любых файлов и изменение любых параметров. Как-то ограничить свободу действий root практически невозможно. С другой стороны, все остальные пользователи системы обычно не имеют большинства необходимых прав, например, прав на установку программ, поскольку это является административной операцией, права на которую есть только у root. Ещё одной распространённой операцией, доступной только суперпользователю, является копирование и изменение файлов в системных папках, куда обычный пользователь доступа не имеет.
Раньше данная проблема решалась достаточно просто: при обладании паролем root можно было зайти в систему под его аккаунтом либо временно получить его права, используя команду su . Потом выполнить все необходимые операции и вернуться обратно под обычного пользователя. В принципе, такая схема работает неплохо, однако у неё есть много существенных недостатков, в частности, невозможно никак (точнее, очень сложно) ограничивать административные привилегии только определённым кругом задач.
Поэтому в современных дистрибутивах Linux вместо root аккаунта для администрирования используется утилита sudo .
В Ubuntu по умолчанию root аккаунт вообще отключён, т.е. вы никаким способом не сможете попасть под root, не включив его. root именно что отключён, т.е. он присутствует в системе, под него всего лишь нельзя зайти. Если вы хотите вернуть возможность использовать root, смотрите ниже пункт о включении root аккаунта.
Что такое sudo
sudo — это утилита, предоставляющая привилегии root для выполнения административных операций в соответствии со своими настройками. Она позволяет легко контролировать доступ к важным приложениям в системе. По умолчанию, при установке Ubuntu первому пользователю (тому, который создаётся во время установки) предоставляются полные права на использование sudo. Т.е. фактически первый пользователь обладает той же свободой действий, что и root. Однако такое поведение sudo легко изменить, об этом см. ниже в пункте про настройку sudo.
Где используется sudo
sudo используется всегда, когда вы запускаете что-то из меню Администрирования системы. Например, при запуске Synaptic вас попросят ввести свой пароль. Synaptic — это программа управления установленным ПО, поэтому для её запуска нужны права администратора, которые вы и получаете через sudo вводя свой пароль.
Однако не все программы, требующие административных привилегий, автоматически запускаются через sudo. Обычно запускать программы с правами администратора приходится вручную.
Запуск графических программ с правами администратора
Для запуска графических программ с правами администратора можно воспользоваться диалогом запуска программ, вызываемым по умолчанию сочетанием клавиш Alt + F2 .
Допустим, нам необходимо запустить файловый менеджер Nautilus с правами администратора, чтобы через графический интерфейс как-то изменить содержимое системных папок. Для этого необходимо ввести в диалог запуска приложений команду
Вместо gksudo можно подставить gksu , кроме того, пользователи KDE должны вместо gksudo писать kdesu . У вас попросят ввести свой пароль, и, если вы обладаете нужными правами, Nautilus запуститься от имени администратора. Запуск любого графического ПО можно производить с правами администратора, просто написав в диалоге запуска
Запуск программ с правами администратора в терминале
Для запуска в терминале команды с правами администратора просто наберите перед ней sudo :
У вас попросят ввести ваш пароль. Будьте внимательны, пароль при вводе никак не отображается, это нормально и сделано в целях безопасности, просто вводите до конца и нажимайте Enter . После ввода пароля указанная команда исполнится от имени root.
Система какое-то время помнит введённый пароль (сохраняет открытой sudo-сессию). Поэтому при последующих выполнениях sudo ввод пароля может не потребоваться. Для гарантированного прекращения сессии sudo наберите в терминале
Кроме того, часто встречаются ошибки, связанные с каналами в Linux. При исполнении команды
с правами root исполнится только cat , поэтому файл result.txt может не записаться. Нужно либо писать sudo перед каждой командой, либо временно переходить под суперпользователя.
Получение прав суперпользователя для выполнения нескольких команд
Иногда возникает необходимость выполнить подряд несколько команд с правами администратора. В этом случае можно временно стать суперпользователем одной из следующих команд:
После этого вы перейдёте в режим суперпользователя (с ограничениями, наложенными через настройки sudo), о чём говорит символ # в конце приглашения командной строки. Данные команды по действию похожа на su , однако: — sudo -s — не меняет домашний каталог на /root, домашним остается домашний каталог пользователя вызвавшего sudo -s, что обычно очень удобно. — sudo -i — сменит так же и домашний каталог на /root.
Для выхода обратно в режим обычного пользователя наберите exit или просто нажмите Ctrl + D .
Использование традиционного root аккаунта и команды su
Ubuntu 11.04 и младше
Для входа под root достаточно задать ему пароль:
Потом на экране входа нажмите Другой… и введите логин (root) и пароль, который вы задали.
Ubuntu 11.10 и старше
Начиная с версии 11.10 был установлен менеджер входа lightdm, и дело со входом под root обстоит немного сложнее.
1. Устанавливаем root пароль. Введите в терминал:
2. Включаем пункт «Введите логин». Введите в терминал:
В конце файла допишите:
3. Перезагружаем lightdm. Введите в терминал:
Все, на экране входа появится пункт «Логин». В поле логин вводим «root», в поле пароль — пароль, который мы задали на первом этапе.
Для обратной блокировки учетной записи root вам потребуется откатить изменения в настройках lightdm, а также заблокировать учетную запись root командой в терминале:
Настройка sudo и прав доступа на выполнение различных команд
sudo позволяет разрешать или запрещать пользователям выполнение конкретного набора программ. Все настройки, связанные с правами доступа, хранятся в файле /etc/sudoers . Это не совсем обычный файл. Для его редактирования необходимо (в целях безопасности) использовать команду
По умолчанию, в нём написано, что все члены группы admin имеют полный доступ к sudo , о чём говорит строчка
Подробнее о синтаксисе и возможностях настройки этого файла можно почитать выполнив
Разрешение пользователю выполнять команду без ввода пароля
Для того, что бы система не запрашивала пароль при определенных командах необходимо в sudoers после строки # Cmnd alias specification добавить строку, где через запятую перечислить желаемые команды с полным путём(путь команды можно узнать, выполнив which имя_команды:
И в конец файла дописать строку
Создание синонимов (alias`ов)
Для того, чтобы не только не вводить пароль для sudo, но и вообще не вводить sudo, сделайте следующее: откройте файл .bashrc, находящейся в вашем домашнем каталоге
и добавьте в конец файла строки
Время действия введённого пароля
Возможно, вы хотите изменить промежуток времени, в течение которого sudo действует без ввода пароля. Этого легко добиться добавив в /etc/sudoers (visudo) примерно следующее:
Здесь sudo для пользователя foo действует без необходимости ввода пароля в течение 20 минут. Если вы хотите, чтобы sudo всегда требовал ввода пароля, сделайте timestamp_timeout равным 0.
sudo не спрашивает пароль
sudo без пароля — чудовищная дыра в безопасности, кому попало разрешено делать что угодно. Если вы разрешили это намеренно — срочно верните обратно как было.
Однако, в некоторых случаях sudo внезапно перестаёт требовать пароль само по себе. Если сделать visudo , то можно увидеть примерно такую строку, которую пользователь вроде бы не добавлял:
Скорее всего, эта катастрофичная строка была добавлена при установке программы типа Connect Manager от МТС или Мегафона. В таком случае, её нужно поменять на строку, разрешающую с правами root запускать только этот Connect Manager, примерно так:
Есть и другие варианты решения проблемы, небольшое обсуждение здесь.
Источник