Root User in Ubuntu- Important Things You Should Know

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.

В дистрибутивах Linux пользовательские привилегии предоставляются путем открытия доступа к root. Наличие таких прав позволяет использовать функциональность операционной системы более широко и выполнять необходимые действия в корневом каталоге.

Давайте детально обсудим, что может суперпользователь в Linux, как настроить root и для чего нужна команда

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: 

Gilles 'SO- stop being evil''s user avatar

asked Aug 16, 2011 at 10:29

LanceBaynes's user avatar

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

Community's user avatar

answered May 12, 2011 at 11:36

Gilles 'SO- stop being evil''s user avatar

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.

Thomas's user avatar

answered Aug 16, 2011 at 11:32

Warren Young's user avatar

Warren Young

16 gold badges177 silver badges168 bronze badges

Anthon's user avatar

42 gold badges164 silver badges222 bronze badges

asked Aug 26, 2013 at 5:35

Ritzz081's user avatar

In Ubuntu root is present but has no password assigned. All you need to do is issue:

sudo passwd root

Дополнительно:  Не включается ноутбук: как восстановить его работу. Почему ноутбук не включается и не загружается: все способы решения проблемы

msw's user avatar

1 gold badge30 silver badges43 bronze badges

answered Aug 26, 2013 at 5:37

vfbsilva's user avatar

3 gold badges27 silver badges42 bronze badges

NOTE: be very careful using root!

To make it clear for your answer:

enter image description here

If you need to use root privilege on terminal after you login.

You need to use

sudo [the command you would like to run] 

or you can use full root by:

sudo su

Community's user avatar

answered Aug 26, 2013 at 6:12

Achu's user avatar

1 gold badge7 silver badges9 bronze badges

Please look at the man page for sudo again; realize that a valid sudo command is:

 sudo /bin/tcsh

Thus you will get a root shell, thus you really DO NOT need to login as root.

answered Aug 26, 2013 at 6:19

mdpc's user avatar

3 gold badges31 silver badges46 bronze badges

I got an easy way to do the same using gksu nautilus.

Using this had helped me to obtain root privilages without using any terminal or so.

answered Oct 9, 2014 at 5:46

Ritzz081's user avatar

2 gold badges2 silver badges5 bronze badges

By default, Ubuntu disables the root account. You must use the sudo command for any tasks requiring root privileges.

This is for your own security, of course. Using the system as root all the time is like running around with a sword in your hand. It increases the chances of messing up things.

Logging in as root is still common in the servers. On the desktop side, it’s quite rare to log in as root. Even Kali Linux has changed it.

Дополнительно:  Как включить подсветку клавиатуры на ноутбуке asus? |

in this guide, I will show you how to log in as a root in your GNOME desktop using Ubuntu.

How to login as a root in the GNOME desktop

I won’t advise login as root on the desktop. You have sudo mechanism for all your root needs. Do it only if you have a good enough reason. This tutorial is for demo purposes only. You have been cautioned.

Step 1: Enable root account

You want to log in as root. But the root account is disabled by default. The first step is to enable it.

Дополнительно:  "Gave up waiting for root device.", (initramfs)

Change the root account password that will eventually enable the root account for you:

sudo passwd root
change the password of root account in ubuntu

It goes without saying that you should not forget the root password.

Step 2: Change GDM configuration

Ubuntu uses GNOME by default and GNOME uses the GDM display manager.

To allow log in as root into GNOME, you need to make some changes in the GDM configuration file located at /etc/gdm3/custom.conf.

Make a backup of the config file:

cp /etc/gdm3/custom.conf /etc/gdm3/custom.conf~

In the worst case, if you somehow mess things up, the back up file can be used to replace the existing one from the TTY.

sudo nano /etc/gdm3/custom.conf
AllowRoot=true
configure GDM on ubuntu

Press Ctrl+X to exit Nano while saving it.

Step 3: Configure PAM authentication

sudo nano /etc/pam.d/gdm-password
auth   required        pam_succeed_if.so user != root quiet_success
Root User in Ubuntu- Important Things You Should Know

Save changes and exit from the nano text editor.

Step 4: Log in as root

Now, reboot your system:

reboot
Login as a root in ubuntu desktop
Logging as root (Click to enlarge)
logged in as a privileged user in Ubuntu

That’s it! Now, you are running your Ubuntu system as a root.

Things you should know when running the system as a root user

There is a reason why Ubuntu disables a root account by default. Want to know why? Here you have it:

Root User in Ubuntu- Important Things You Should Know

Root User in Ubuntu- Important Things You Should Know

Either you run commands with root privilege like this:

sudo any_command
sudo su

What is root user? Why is it locked in Ubuntu?

Root User Ubuntu

You don’t need to have root privilege for your daily tasks like moving file in your home directory, downloading files from internet, creating documents etc.

Take this analogy for understanding it better. If you have to cut a fruit, you use a kitchen knife. If you have to cut down a tree, you have to use a saw. Now, you may use the saw to cut fruits but that’s not wise, is it?

Does this mean that you cannot be root in Ubuntu or use the system with root privileges? No, you can still have root access with the help of ‘sudo’ (explained in the next section).

How to run commands as root user in Ubuntu?

apt update
Reading package lists... Done
E: Could not open lock file /var/lib/apt/lists/lock - open (13: Permission denied)
E: Unable to lock directory /var/lib/apt/lists/
W: Problem unlinking the file /var/cache/apt/pkgcache.bin - RemoveCaches (13: Permission denied)
W: Problem unlinking the file /var/cache/apt/srcpkgcache.bin - RemoveCaches (13: Permission denied)

So, how do you run commands as root? The simple answer is to add sudo before the commands that require to be run as root.

sudo apt update
[email protected]:~$ sudo apt update
[sudo] password for abhishek: 

If you are absolutely new to Linux, you might be surprised that when you start typing your password in the terminal, nothing happens on the screen. This is perfectly normal because as the default security feature, nothing is displayed on the screen. Not even the asterisks (*). You type your password and press enter.

Bottom line:
To run commands as root in Ubuntu, add sudo before the command.
When asked for password, enter your account’s password.
When you type the password on the screen, nothing is visible. Just keep on typing the password and press enter.

How to become root user in Ubuntu?

The sudo command allows you to simulate a root login shell with this command:

sudo -i
[email protected]:~$ sudo -i
[sudo] password for abhishek: 
[email protected]:~# whoami
root
[email protected]:~# 

You’ll notice that when you switch to root, the shell command prompt changes from $ (dollar key sign) to # (pound key sign). This makes me crack a (lame) joke that pound is stronger than dollar.

sudo su

If you try to use the su command without sudo, you’ll encounter ‘su authentication failure’ error.

exit

How to enable root user in Ubuntu?

sudo passwd root

Again, this is not recommended and I won’t encourage you to do that on your desktop. If you forgot it, you won’t be able to change the root password in Ubuntu again.

sudo passwd -dl root

I hope you have a slightly better understanding of the root concept now. If you still have some confusion and questions about it, please let me know in the comments. I’ll try to answer your questions and might update the article as well.

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.

Other programs

Calife

Op

Super

Editing a file as root

See How do I edit a file as root?

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.)

Переключение на суперпользователя

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

Примерно так же работает и команда , но она обладает дополнительными аргументами, которые следует уточнить:

  • -c – позволяет выполнить команду;
  • -g – устанавливает группу для пользователя;
  • -G – дополнительные группы для юзера;
  • -l —login – один из режимов входа, при котором происходит переключение домашнего каталога;
  • -p – сохранение переменных окружения;
  • -s – выбор оболочки для выхода.

Вы уже сами решайте, какой вариант хотите использовать, и готовы ли смириться со всеми ограничениями и недостатками, которые накладывает каждый из них.

Предназначение root-прав в Linux

Права обычного пользователя в Linux крайне ограничены. Он может управлять только своим каталогом и открывать для чтения определенные файлы из корня. Доступ для их изменения или установки программ отсутствует, что делает привилегии суперпользователя крайне важными при настройке ОС и решении разных проблем. Обычный пользователь ограничивается следующим набором прав:

  • чтение, запись и изменение любых атрибутов пользовательской папки;
  • то же самое и для каталога
  • выполнение программ в любом месте, где нет ограничений;
  • чтение файлов с соответствующим атрибутом для всех пользователей.

При наличии рут-прав у юзера появляется гораздо больше возможностей и расширяются границы взаимодействия с операционной системой. Становятся доступными любые действия со всеми папками и файлами.

Комьюнити теперь в Телеграм

Подпишитесь и будьте в курсе последних IT-новостей

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.

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 для установки приложений и защиты системы от случайных изменений, которые могут внести другие пользователи компьютера.

С серверной частью все гораздо сложнее, поскольку рут как таковой не предоставляет полной защиты. Часто используемые пароли взламываются путем перебора или поиском бэкдора. Поэтому не стоит полагаться исключительно на защиту паролем, если вы владеете файлами сайтов или используете сервер для других целей. Займитесь настройкой файрвола, если это повысит уровень защиты.

This answer has been deemed insecure. See comments below

  1. Create a new script file (replace create_dir.sh with your desired script name):

    vim ~/create_dir.sh
    
  2. mkdir /abc
    

    Note: Don’t add sudo to these commands. Save and exit (using :wq!)

  3. Assign execute permissions to it using:

    sudo chmod u+x create_dir.sh
    
  4. Make changes so that this script doesn’t require a password.

    1. Open the sudoers file:

      sudo visudo -f /etc/sudoers
      
    2. ahmad ALL=(root) NOPASSWD: /home/ahmad/create_dir.sh
      
  5. 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.

Eldamir's user avatar

answered Sep 14, 2013 at 5:18

M. Ahmad Zafar's user avatar

myusername ALL=(ALL) NOPASSWD: /path/to/executable

answered May 12, 2011 at 8:30

musiKk's user avatar

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.

Thomas's user avatar

8 gold badges26 silver badges32 bronze badges

answered Mar 25, 2017 at 9:10

linuxgnuru's user avatar

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.

Toby Speight's user avatar

2 gold badges25 silver badges48 bronze badges

answered Jun 17, 2015 at 20:48

Lyoneel's user avatar

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.

peterph's user avatar

2 gold badges69 silver badges75 bronze badges

answered Jul 18, 2014 at 23:54

Sepero's user avatar

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

Cherry's user avatar

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.

Michael Mrozek's user avatar

answered May 12, 2011 at 8:31

Caleb's user avatar

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.

peterph's user avatar

2 gold badges69 silver badges75 bronze badges

answered Jul 18, 2013 at 17:44

Luc's user avatar

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

Lakindu Akash's user avatar

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

Paulo Tomé's user avatar

6 gold badges26 silver badges37 bronze badges

answered Feb 14, 2020 at 15:13

Madhusudhan Kasula's user avatar

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

Basile Starynkevitch's user avatar

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

dragon788's user avatar

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.

  1. Create a shell script where you call the command without sudo.
  2. 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).
  3. Add the exception to sudoers using visudo:

  4. 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

Koit Saarevet's user avatar

Команда sudo и примеры ее использования

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

Использование команды sudo в Linux

Самый простой пример использования – запуск программы от имени суперпользователя. Для этого вводится:

 sudo program \\   program – название приложения, которое вы хотите запустить

применяется для установки софта, команда в таком случае обретает вид:

sudo apt install program

В следующем разделе статьи речь пойдет о передаче прав суперпользователя, что тоже реализуемо при помощи . Я рассмотрю два полезных аргумента. Советую ознакомиться с ними, если хотите упростить выполнение действий через Терминал.

VDS Timeweb арендовать

Предоставление и отзыв прав суперпользователя

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

Создание нового пользователя с root

Допустим, что вы, единственный юзер в Linux, хотите создать еще одну учетную запись с правами суперпользователя. В таком случае алгоритм действий обретет следующий вид:

sudo Linux

  1. Откройте Терминал и введите команду
  2. В консоли появятся инструкции по созданию нового пользователя. Присвойте пароль и подтвердите действие, чтобы завершить создание.
  3. Добавьте новую учетную запись в группу sudo, введя user здесь тоже понадобится заменить).
  4. Проверьте выполненные действия, переключившись на новую учетную запись через . Для подтверждения введите пароль (при вводе символы не отображаются на экране).
  5. Выполните любую команду с и убедитесь, что все прошло успешно.

Для существующей учетной записи

Если учетная запись уже добавлена, в консоли остается ввести только одну команду, чтобы добавить пользователя в группу sudo и разрешить ему получение рут-прав. Сама команда представлена ниже, вам остается только скопировать ее и поменять имя юзера.

Предоставление прав суперпользователя существующей учетной записи в Linux

Используйте предыдущую инструкцию для проверки внесенных изменений.

Откат прав суперпользователя

Если вдруг вы решили, что одна из учетных записей больше не должна состоять в группе sudo, отзовите права, введя команду:

Откат прав суперпользователя в Linux

Это была вся основная информация о правах суперпользователя в Linux. Вы знаете, что дают такие привилегии, как их правильно использовать и управлять пользователями. В качестве рекомендации скажу, что всегда нужно читать текст ошибок, появляющихся в Терминале, если что-то пошло не так. Это позволит вам быстрее решить проблему без траты времени на поиски в Google.

Оцените статью
Master Hi-technology
Добавить комментарий