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.
Для запуска и корректной работы различных административных консольных и графических программ в GNU-Linux (просто Linux далее) могут потребоваться права администратора. Получить права root их можно при помощи нескольких основных способов.
В дистрибутивах Linux пользовательские привилегии предоставляются путем открытия доступа к root. Наличие таких прав позволяет использовать функциональность операционной системы более широко и выполнять необходимые действия в корневом каталоге.
Давайте детально обсудим, что может суперпользователь в Linux, как настроить root и для чего нужна команда
I am using Trisquel GNU/Linux-Libre which comes with Gnome3 Flashback Desktop Environment.
I know that I can run GUI application as root by sudo
& gksudo
but I want to know that How do I run GUI applications as root with the help of pkexec
?
When I tries to run gedit
(or any other application like:nautilus
) by pkexec gedit
then It prompts for password for authentication:-
After entering password it exit with error:-
$ pkexec gedit
error: XDG_RUNTIME_DIR not set in the environment.
(gedit:6135): Gtk-WARNING **: cannot open display:
So, It seems something is going wrong with display environment.
I’ve also tried with DISPLAY=:0 pkexec gedit
but doesn’t work.
Now I don’t know What to do in order to accomplish this.
Thus, Help me to find out How to run GUI applications as root by means of pkexec
. Or Is this possible or not?
BTW, Inspired by gparted-pkexec
command which works fine. How gparted
use pkexec
?
I need to run something as sudo without a password, so I used visudo
and added this to my sudoers
file:
MYUSERNAME ALL = NOPASSWD: /path/to/my/program
Then I tried it out:
$ sudo /path/to/my/program
[sudo] password for MYUSERNAME:
asked Aug 16, 2011 at 10:29
97 gold badges249 silver badges348 bronze badges
If there are multiple matching entries in /etc/sudoers
, sudo uses the last one. Therefore, if you can execute any command with a password prompt, and you want to be able to execute a particular command without a password prompt, you need the exception last.
myusername ALL = (ALL) ALL
myusername ALL = (root) NOPASSWD: /path/to/my/program
answered May 12, 2011 at 11:36
Having done that, sudo
will prompt for a password normally for all commands except /path/to/my/program
, which it will always let you run without asking for your password.
answered Aug 16, 2011 at 11:32
Warren Young
16 gold badges177 silver badges168 bronze badges
- 1. Overview
- 2. Running as Root in GUI Applications
- 3. Classic Approach With gksu
- 3.1. Installation
- 3.2. Usage
- 4. PAM
- 4.1. Configuring PAM for su/sudo
- 5. Running GUI Program as Another User Using sudo
- 6. Using the GVfs Admin Backend
- 7. Conclusion
- Вход с правами администратора root — режим «Super User» (su)
- Запуск программ с правами администратора root из графического диалога
- This answer has been deemed insecure. See comments below
- Переключение на суперпользователя
- Logging in as root
- 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
- Other programs
- Calife
- Op
- Super
- Sudo (preferred when not running a graphical display)
- Безопасность использования прав суперпользователя
- Предназначение root-прав в Linux
- Команда sudo и примеры ее использования
- Предоставление и отзыв прав суперпользователя
- Создание нового пользователя с root
- Для существующей учетной записи
- Откат прав суперпользователя
- Права администратора без авторизации администратора root — режим «Super User Do» (sudo)
1. Overview
In this tutorial, we’ll discuss how we can run the GUI applications in Linux as root. We’ll make use of the different utilities that come pre-installed with most Linux distributions such as gksu and sudo.
2. Running as Root in GUI Applications
3. Classic Approach With gksu
gksu is a GTK-based front-end for su and sudo. It’s not used in the newer Linux distributions. However, there are some distributions that use gksu as the default handler for opening GUI applications as root.
3.1. Installation
If gksu isn’t available on our Linux machine, we can install it from the official repositories using a package manager such as apt or yum.
On Ubuntu, it’s already pre-installed. However, on Ubuntu-based distributions we can install it using apt:
$ apt install gksu
Similarly, on Fedora, Fedora-based distributions, and RHEL, we can use yum:
$ yum install gksu
3.2. Usage
Once installed, we can go ahead and launch a GUI application using gksu from the command line:
$ gksu gedit /etc/fstab
Upon entering the command, we should see a prompt asking for our password:
Additionally, we configure gksu to use either sudo or su as a backend. We can run gksu as su using the –su-mode or -w option:
$ gksu --su-mode gparted
Similarly, we can use the –sudo-mode or -S to use gksu in sudo mode. As a side note, gksu on Ubuntu uses sudo as its default backend.
In the next sections, we’ll take a look at the other alternatives because gksu isn’t available on most modern Linux distributions.
4. PAM
4.1. Configuring PAM for su/sudo
The configuration files for PAM are located in the /etc/pam.d directory. In this directory, we’ll create a new file named su. Here, we’ll put su specific configuration to run GUI programs as root:
session optional pam_xauth.so
Now, we should be able to launch GUI programs from the command line as su:
$ su -
Password:
# gparted
This configuration is applicable to sudo as well.
$ glxgears
No protocol specified
Error: couldn't open display :0
In this case, we’ll need to do two things if we’re using the X server:
- specify the $DISPLAY environment variable, which is usually :0
- provide proper authentication information through $XAUTHORITY, which defaults to ~/.Xauthority
$ env | grep -E "DISPLAY|XAUTHORITY"
DISPLAY=:0
XAUTHRORITY=/home/hey/.Xauthority
However, if they default to a wrong value, then we’ll need to export these variables to point to proper values in our shell profile.
5. Running GUI Program as Another User Using sudo
$ sudo -u foo -H firefox
- -u specifies the user
- -H sets the $HOME variable to the target user’s home directory
The above command has no issues whatsoever. However, we might get a familiar error that we discussed before:
No protocol specified
Error: couldn't open display :0
$ xhost si:localuser:foo
$ xhost si:localuser:root
6. Using the GVfs Admin Backend
$ gedit admin:///etc/fstab
7. Conclusion
Вход с правами администратора root — режим «Super User» (su)
Команда su
, отданная в консоли Linux вызовет запрос пароля администратора root компьютера и, после его ввода, Ваш вход с правами администратора компьютера в той же консольной сессии. Это даёт возможность работать далее от имени администратора системы с любыми консольными командами и программами.
Настоятельно не рекомендуется запускать графическую систему X11, рабочие столы Gnome, KDE и т.п. от имени администратора: это может стать угрозой безопасности ваших данных и, часто, причиной некорректной работы операционной системы.
Запуск программ с правами администратора root из графического диалога
Для того, чтобы запускать программы от имени администратора root, в том числе и в основном графические, можно использовать графические же утилиты kdesudo (программа, написанная на Qt для KDE) и gksu (программа с GTK-интерфейсом для Gnome, XFCE и т.п.). Использовать оба варианта запуска графических программ от имени администратора очень просто: через консоль путём ввода приставки kdesudo
(или gksu
) перед именем программы, как в случае с sudo
: gksu synaptic
This answer has been deemed insecure. See comments below
-
Create a new script file (replace
create_dir.sh
with your desired script name):vim ~/create_dir.sh
-
mkdir /abc
Note: Don’t add
sudo
to these commands. Save and exit (using:wq!
) -
Assign execute permissions to it using:
sudo chmod u+x create_dir.sh
-
Make changes so that this script doesn’t require a password.
-
Open the
sudoers
file:sudo visudo -f /etc/sudoers
-
ahmad ALL=(root) NOPASSWD: /home/ahmad/create_dir.sh
-
-
Now when running the command add
sudo
before it like:sudo ./create_dir.sh
This will run the commands inside the script file without asking for a password.
answered Sep 14, 2013 at 5:18
myusername ALL=(ALL) NOPASSWD: /path/to/executable
answered May 12, 2011 at 8:30
3 silver badges14 bronze badges
If you want to avoid having to use sudo nor have to change the sudoers config file, you can use:
sudo chown root:root path/to/command/COMMAND_NAME
sudo chmod 4775 path/to/command/COMMAND_NAME
This will make the command run as root without the need of sudo.
8 gold badges26 silver badges32 bronze badges
answered Mar 25, 2017 at 9:10
3 silver badges6 bronze badges
If you have an distro like Manjaro, you must deal first with a file that overrides the definition of /etc/sudoers
; you may delete it or work directly with that file to add your new configurations.
This file is:
sudo cat /etc/sudoers.d/10-installer
The ONLY way to see it is under root privileges; you cannot list this directory without it. This file is Manjaro specific: you may find this configuration with a different name, but in same directory.
Ignore authentication for a group:
%group ALL=(ALL) NOPASSWD: ALL
youruser ALL=(ALL) NOPASSWD: ALL
youruser ALL=(ALL) NOPASSWD: /path/to/executable
QUICK NOTE: You are opening a door to use sudo
without authentication, which means you can run everything modifying everything on your system; use it with responsibility.
2 gold badges25 silver badges48 bronze badges
answered Jun 17, 2015 at 20:48
1 silver badge6 bronze badges
Verify that sudo is not aliased. Run like this
/usr/bin/sudo /path/to/my/program
For example a shell alias like this one:
alias sudo="sudo env PATH=$PATH"
may cause this behaviour.
2 gold badges69 silver badges75 bronze badges
answered Jul 18, 2014 at 23:54
3 gold badges20 silver badges29 bronze badges
In the script sudoers
which is inside /etc/ uncomment the line given below:
#!/bin/bash
ALL ALL = NOPASSWD: /path/of/the/script/which/you/want/to/run/as/root
This is the safest way to run the script with root permission.
answered Sep 22, 2020 at 15:25
When you execute your script you need to run it as sudo /path/to/my/script
.
Edit: Based on your comment to another answer, you want to run this from an icon. You will need to create a .desktop
file that executes your program with sudo, just like on the terminal.
You could also consider using gtk-sudo
for a visual password prompt.
You should probably consider the idea that you shouldn’t be running things as root and that changing the system farther down the road so that you don’t need root permissions at all would be a better way to go.
answered May 12, 2011 at 8:31
18 gold badges196 silver badges226 bronze badges
This solved the issue for me (also tried some of the other answers, that might have helped):
The script I was calling was in /usr/bin
, a directory that I don’t have write permissions to (though I can usually read any files there). The script was chmodded +x (executable permisison), but it still didn’t work. Moving this file to a path in my home directory, instead of /usr/bin
, I was finally able to call it with sudo without entering a password.
Also something I doubted about (clarifying for future readers): You need to run your script as sudo. Type sudo
when calling the script. Don’t use sudo
for the command inside your script that actually needs root (changing keyboard backlight in my case). Perhaps that also works, but you don’t need to, and it seems like a better solution not to.
2 gold badges69 silver badges75 bronze badges
answered Jul 18, 2013 at 17:44
3 gold badges24 silver badges37 bronze badges
%sudo ALL=(root) NOPASSWD: /path/to/your/program
Note that %sudo make it.
answered Mar 2, 2019 at 17:11
Alternately you can use python pudo package.
user$ sudo -H pip3 install pudo # you can install using pip2 also
Below is the code snippet for using in python automation for running commands under root privilege:
user$ python3 # or python2
>>> import pudo
>>> (ret, out) = pudo.run(('ls', '/root')) # or pudo.run('ls /root')
>>> print(ret)
>>> 0
>>> print(out)
>>> b'Desktop\nDownloads\nPictures\nMusic\n'
Below is the cmd example for running commands under root privilege:
user$ pudo ls /root
Desktop Downloads Pictures Music
6 gold badges26 silver badges37 bronze badges
answered Feb 14, 2020 at 15:13
Another possibility might be to install, configure, then use the super command to run your script as
super /path/to/your/script
If you want to run some binary executable (e.g. that you have compiled into ELF binary from some C source code) -which is not a script- as root, you might consider making it setuid (and actually /bin/login
, /usr/bin/sudo
and /bin/su
and super
are all using that technique). However, be very careful, you could open a huge security hole.
You’ll use chmod u+s
(read chmod(1)) when installing such a binary.
But be very careful.
Read many things about setuid, including Advanced Linux Programming, before coding such a thing.
Notice that a script, or any shebang-ed thing, cannot be setuid. But you could code (in C) a small setuid-binary wrapping it.
Be aware that on Linux, application code interact with the Linux kernel using syscalls(2). Most of them could fail, see errno(3). A lot of Linux applications (e.g. GNU bash, GNU make, GNU gdb, GNOME) are open source : you are allowed to download then study and contribute to their source code.
answered Jul 24, 2017 at 11:00
Ideally if you are customizing what commands can be run via sudo
you should be making these changes in a separate file under /etc/sudoers.d/
instead of editing the sudoers
file directly. You should also always use visudo
to edit the file(s). You should NEVER grant NOPASSWD
on ALL
commands.
Example:
sudo visudo -f /etc/sudoers.d/mynotriskycommand
Then save and exit and visudo
will warn you if you have any syntax errors.
You can control the file name ordering by using a prefix of 00-99 or aa/bb/cc, though also keep in mind that if you have ANY files that don’t have numeric prefix, they will load after the numbered files, overriding the settings. This is because depending on your language settings the «lexical sorting» the shell uses sorts numbers first and then may interleave upper and lowercase when sorting in «ascending» order.
answered May 22, 2017 at 21:26
6 silver badges14 bronze badges
but if the structure is command option1 value1
, where value1
can vary, you would need to have explicit sudoers lines for each possible value of value1
. Shell script provides a way around it.
This answer was inspired by M. Ahmad Zafar’s answer and fixes the security issue there.
- Create a shell script where you call the command without
sudo
. - Save the script in a root-privileged folder (e.g.
/usr/local/bin/
), make the file root-owned (e.g.chown root:wheel /usr/local/bin/script_name
) with no write access for others (e.g.chmod 755 /usr/local/bin/script_name
). -
Add the exception to sudoers using visudo:
-
Run your script
sudo script_name
.
For example, I want to change display sleep timeout on macOS. This is done using:
sudo pmset displaysleep time_in_minutes
I consider changing the sleep timeout an innocent action that doesn’t justify the hassle of password typing, but pmset
can do many things and I’d like to keep these other things behind the sudo password.
#!/bin/bash
if [ $# -eq 0 ]; then
echo 'To set displaysleep time, run "sudo ds [sleep_time_in_minutes]"'
else
if [[ $1 =~ ^([0-9]|[1-9][0-9]|1[0-7][0-9]|180)$ ]]; then
pmset displaysleep $1
else
echo 'Time must be 0..180, where 0 = never, 1..180 = number of minutes'
fi
fi
sudo ds 3
#!/bin/bash
pmset displaysleep $1
answered Mar 30, 2019 at 20:17
Переключение на суперпользователя
Еще раз уточню, что команда идеально подходит для получения необходимых привилегий без переключения учетной записи. Ее можно использовать как для выполнения одного действия, так и нескольких. Если вы желаете временно получить рут-права через эту команду, введите . В первом случае домашний каталог остается текущим, а во втором меняется на /root.
Примерно так же работает и команда , но она обладает дополнительными аргументами, которые следует уточнить:
- -c – позволяет выполнить команду;
- -g – устанавливает группу для пользователя;
- -G – дополнительные группы для юзера;
- — -l —login – один из режимов входа, при котором происходит переключение домашнего каталога;
- -p – сохранение переменных окружения;
- -s – выбор оболочки для выхода.
Вы уже сами решайте, какой вариант хотите использовать, и готовы ли смириться со всеми ограничениями и недостатками, которые накладывает каждый из них.
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.
Running a graphical command as root
See also Wikipedia.
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.
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
kdesu -c 'command --option argument'
and enter the root password, or type
kdesudo -c 'command --option argument'
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
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
gksu command --option argument
and enter the root password, or type
gksudo command --option argument
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.
su -c 'service apache restart'
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.
$ su
# command 1
# command 2
...
# exit
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.)
Editing a file as root
See How do I edit a file as root?
Other programs
Calife
Op
Super
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.
sudo service apache restart
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:
$ sudo -i
# command 1
# command 2
...
# exit
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.
Безопасность использования прав суперпользователя
Если с предназначением root-прав в Linux все понятно, то вот к безопасности их использования есть вопросы. В основном, относится это к серверным машинам, поскольку риск взлома домашнего компьютера очень мал, да и кому нужны файлы обычного пользователя, чтобы ради этого затевать процедуру взлома. Если вы используете Linux как обычную операционную систему, работаете с документами и стандартными программами, используйте root для установки приложений и защиты системы от случайных изменений, которые могут внести другие пользователи компьютера.
С серверной частью все гораздо сложнее, поскольку рут как таковой не предоставляет полной защиты. Часто используемые пароли взламываются путем перебора или поиском бэкдора. Поэтому не стоит полагаться исключительно на защиту паролем, если вы владеете файлами сайтов или используете сервер для других целей. Займитесь настройкой файрвола, если это повысит уровень защиты.
Предназначение root-прав в Linux
Права обычного пользователя в Linux крайне ограничены. Он может управлять только своим каталогом и открывать для чтения определенные файлы из корня. Доступ для их изменения или установки программ отсутствует, что делает привилегии суперпользователя крайне важными при настройке ОС и решении разных проблем. Обычный пользователь ограничивается следующим набором прав:
- чтение, запись и изменение любых атрибутов пользовательской папки;
- то же самое и для каталога
- выполнение программ в любом месте, где нет ограничений;
- чтение файлов с соответствующим атрибутом для всех пользователей.
При наличии рут-прав у юзера появляется гораздо больше возможностей и расширяются границы взаимодействия с операционной системой. Становятся доступными любые действия со всеми папками и файлами.
Комьюнити теперь в Телеграм
Подпишитесь и будьте в курсе последних IT-новостей
Команда sudo и примеры ее использования
тесно связана с root в Linux, поскольку отвечает за передачу прав суперпользователя и позволяет от его имени выполнять команды в Терминале. Существует несколько ее вариаций, использующихся при разных обстоятельствах. Подходит эта команда как для выполнения всего одного действия, так и для передачи прав на всю текущую сессию.
Самый простой пример использования – запуск программы от имени суперпользователя. Для этого вводится:
sudo program \\ program – название приложения, которое вы хотите запустить
применяется для установки софта, команда в таком случае обретает вид:
sudo apt install program
В следующем разделе статьи речь пойдет о передаче прав суперпользователя, что тоже реализуемо при помощи . Я рассмотрю два полезных аргумента. Советую ознакомиться с ними, если хотите упростить выполнение действий через Терминал.
Предоставление и отзыв прав суперпользователя
Каждому пользователю в Linux можно предоставить root-права, добавив его в соответствующую группу. Точно так же их можно и отнять, если вдруг это понадобится. Рассмотрю три варианта действий.
Создание нового пользователя с root
Допустим, что вы, единственный юзер в Linux, хотите создать еще одну учетную запись с правами суперпользователя. В таком случае алгоритм действий обретет следующий вид:
- Откройте Терминал и введите команду
- В консоли появятся инструкции по созданию нового пользователя. Присвойте пароль и подтвердите действие, чтобы завершить создание.
- Добавьте новую учетную запись в группу sudo, введя user здесь тоже понадобится заменить).
- Проверьте выполненные действия, переключившись на новую учетную запись через . Для подтверждения введите пароль (при вводе символы не отображаются на экране).
- Выполните любую команду с и убедитесь, что все прошло успешно.
Для существующей учетной записи
Если учетная запись уже добавлена, в консоли остается ввести только одну команду, чтобы добавить пользователя в группу sudo и разрешить ему получение рут-прав. Сама команда представлена ниже, вам остается только скопировать ее и поменять имя юзера.
Используйте предыдущую инструкцию для проверки внесенных изменений.
Откат прав суперпользователя
Если вдруг вы решили, что одна из учетных записей больше не должна состоять в группе sudo, отзовите права, введя команду:
Это была вся основная информация о правах суперпользователя в Linux. Вы знаете, что дают такие привилегии, как их правильно использовать и управлять пользователями. В качестве рекомендации скажу, что всегда нужно читать текст ошибок, появляющихся в Терминале, если что-то пошло не так. Это позволит вам быстрее решить проблему без траты времени на поиски в Google.
Права администратора без авторизации администратора root — режим «Super User Do» (sudo)
Команда sudo
, в качестве приставки к имени основной программы, предоставляет возможность пользователю выполнять команды от имени администратора, не авторизуясь непосредственно как root. В большинстве случаев наличие в системе настроенного режима sudo делает работу от имени администратора практически ненужной, а паролем для запуска sudo чаще всего становится пароль первого созданного в системе пользователя («sudoer‘а»).