- What is «root»?
- How to become «root»?
- How to switch to root on Linux
- How to Switch to Root User on Linux
- Closing Thoughts
- Related Linux Tutorials:
- How to become root in Linux
- Logging in as root
- Running commands as root without the root password
- Related information
- Как получить права суперпользователя в Ubuntu
- Запуск прав суперпользователя командой sudo
What is «root»?
root is a user existing on every Linux system.
To be more precise, it is a special user — the super user!
root is the only user that has privileges to do everything.
In contrast to the two types of user accounts you can create (administrator users and restricted users), it exists by default and can neither be renamed or deleted. Usually, logging in as root is disabled for security reasons.
You may think that your admin user is the most powerful account on your machine and may do everything, but that is wrong. Simplified and in general, your admin user is almost equal to a restricted user in permissions. It also only has writing permissions in its own home folder and also may not change system wide settings.
However, the admin users have one special and important privilege:
How to become «root»?
As logging in as root is prohibited on Ubuntu per default, there has to be another way to become root in order to be able to perform important system wide administrative tasks.
Administrator user accounts have the permission to use the sudo command to execute a single command as root/with root privileges.
It is simple. Just write sudo before every terminal command that needs special elevated permissions to run and execute it. It will show you a prompt and ask for a password like this (my username is bytecommander ):
[sudo] password for bytecommander:
Note that you have to enter the password of your own admin account and not the (by default not existing) root user’s password. It is also configured to only ask once every 15 minutes for your password, so the second invocation of sudo will run the command immediately. However, if you close the terminal window, the sudo ticket is also reset. Furthermore is it important for you to know that there will be no display output when you type the password, not even stars (*) will appear to symbolize the entered characters. Just type it and hit Enter .
Let me give you an example on how/when to use sudo:
- apt-get is the command-line tool to run software updates and install new packages. This affects the whole system and therefore requires root permissions. Therefore, whenever we need to invoke apt-get , we have to do this with sudo :
would for example install the famous media player VLC (after asking for your password, if you did not enter it in the current terminal window within the last 15 minutes). If we ran the command as normal user without sudo ( apt-get install vlc only), it would result in this error:
E: Could not open lock file /var/lib/dpkg/lock — open (13: Permission denied)
E: Unable to lock the administration directory (/var/lib/dpkg/), are you root?
How to proceed with graphical applications instead of terminal commands?
Sometimes you need to run a graphical application (such as e.g. the Files manager, a special editor or an additional tweak tool) with root privileges. In this case, please do not use sudo , as this is only for terminal commands. For several reasons I don’t want to discuss here, it may lead to severe problems (see this answer for further explanations).
So for graphical applications, there are other commands which are safer to run GUI apps and which provide a graphical popup-window to request your password instead of a terminal window. Those are mainly gksu and gksudo . Experts are arguing which of them is to prefer, but for the normal Ubuntu user, both can be taken equally. The syntax is the same as with sudo . For example, we can run the file manger Nautilus with root privileges by:
How to switch to root on Linux
Linux users will inevitably need to log into the root account, or use administrator privileges, quite frequently. Tasks like installing or removing software, configuring system settings, adjusting file permissions, and many others usually require access to the root user account in order to perform. The root account can be accessed either by logging directly into the account, or by using the sudo Linux command to temporarily access root and execute a command with administrator privileges. In this tutorial, we will show you how to change to the root account on a Linux system, and how to use sudo to execute commands with root privileges.
In this tutorial you will learn:
- How to log in to the root account
- How to use the sudo command
- How to open a new terminal as the root user
Category | Requirements, Conventions or Software Version Used |
---|---|
System | Any Linux distro |
Software | N/A |
Other | Privileged access to your Linux system as root or via the sudo command. |
Conventions | # – requires given linux commands to be executed with root privileges either directly as a root user or by use of sudo command $ – requires given linux commands to be executed as a regular non-privileged user |
How to Switch to Root User on Linux
Here are a few different methods to switch to the root user on Linux. Depending on your Linux distribution and the way your user is configured (i.e., whether they have sudo access or not), you may find that one method works better than another, so try them all.
- The majority of Linux distributions come with the sudo convention configured by default for the user that is set up during installation. If your user has access to the sudo command, then you can switch to the root account by appending the -i option, like so:
After providing your sudo password, you will be logged into the root account and no longer required to continue prefacing your commands with sudo in order to run them with root privileges.
Alternatively, there is no reason to log into the root user account if you have access to the sudo command and simply want to run a few commands as the root user. This is actually the recommended approach, as it is more secure than having users to log into the root account directly. For example, to run a command as root, preface it with sudo :
Although we are running this command as an ordinary user, the whoami command shows us the effective user that is running the command, which is root.
DID YOU KNOW?
See our tutorial on giving a user sudo permissions if your account has not yet been configured to use the sudo command.
WARNING
The above command will only work if the root account has a password configured. On some systems, the root account does not have a password by default, and instead is expected to be accessed strictly via sudo as shown in the above methods.
If your root account does not have a password and you need to set one, you can execute the following command. Note that this is going against security recommendations.
Closing Thoughts
In this tutorial, we saw how to switch to the root user account on a Linux system. The recommended approach is to use the sudo command in order to execute commands with root privileges, but we can also log directly into the root user account, either with the sudo -i or su — commands, depending on how our system and user account has been configured.
Related Linux Tutorials:
How to become root in Linux
On every Linux system, the root account is a special user with administrative rights. Logging in as root (or executing commands with root privileges) is necessary for many tasks. If you need to perform tasks as the root user, make sure you fully understand the commands you are running, and what consequences they have. A single careless or malformed command, run as root, can make the entire operating system unusable. Do your research, and always double-check every command before pressing Enter .
Logging in as root
The root account is similar to any other account in that it has a username («root») and a password. If you know root’s password, you can use it to log into the root account from the command line.
There is a special command named su (for «super user,» or «switch user») that lets you run commands as the root account temporarily. From the command line, type:
Enter the password once prompted for the password. If successful, you are switched to the root user and can run commands with full system privileges.
Be careful while logged in as root. It is easy to forget you’re currently the root user, and you might inadvertently run a command thinking you are only a mere mortal. One way to remind yourself if you are root or not is to check your command prompt. Many systems end their command prompt with a dollar sign («$«) if you’re logged in as a normal user and a pound sign («#«) if you’re root.
Or, you can use the whoami command to determine the account you are using.
When finished with your administrative tasks, you can run the exit or logout command to return to your standard user account.
When logging in as root, it is often useful to use a single dash after the su command, like this:
This command simulates a complete root login. It executes all of the root user’s shell initialization scripts and sets all environment variables as if the root logged in to a fresh shell session. Depending on what task you need to perform, and how root is configured, this form of the su command might be optimal for you.
Running commands as root without the root password
It is possible, and often preferable, to run commands as root without logging into the root account using the sudo command, which stands for «superuser do.» If you prefix a command with sudo, you are prompted for your password (not the root password), and your name is checked against a special file called sudoers. If your account is listed there, your command runs with root privileges.
Using sudo makes it difficult to forget you’re root since you’re not logged in to the root account, and are never going to forget to log out. Also, typing sudo every time you run a potentially destructive command reminds you to be extra careful and double check yourself.
If you need to add a user to the sudoers list, use the visudo command that requires root privileges to run, and lets you safely edit the sensitive sudoers file.
Related information
Как получить права суперпользователя в Ubuntu
В создании этой статьи участвовала наша опытная команда редакторов и исследователей, которые проверили ее на точность и полноту.
Команда контент-менеджеров wikiHow тщательно следит за работой редакторов, чтобы гарантировать соответствие каждой статьи нашим высоким стандартам качества.
Количество просмотров этой статьи: 240 738.
Чтобы запускать административные задачи на Linux, у вас должны быть права суперпользователя (права root). В большинстве дистрибутивов Linux присутствует отдельная учетная запись суперпользователя, но в Ubuntu она по умолчанию отключена. Это позволяет предотвратить случайные ошибки и защитить систему от проникновения. Чтобы запустить команды, которые требуют административный доступ, используйте команду sudo .
Запуск прав суперпользователя командой sudo
Нажмите комбинацию клавиш Ctrl + Alt + T , чтобы открыть окно терминала. Так как в Ubuntu права суперпользователя по умолчанию отключены, вы не сможете воспользоваться командой su и получить административные права, как в прочих дистрибутивах Linux. [1] X Источник информации Вместо этого, вам сначала необходимо запустить команду sudo .
- Пример: команда sudo /etc/init.d/networking stop прекращает работу сети, а sudo adduser добавляет в систему нового пользователя. Обе эти команды требуют прав суперпользователя.
- Перед тем, как sudo выполнит команду, вы должны будете ввести пароль. Linux хранит пароль в течение 15 минут, так что вам не придется вводить их постоянно.
- Пример: введите gksudo gedit /etc/fstab , чтобы открыть файл «fstab» в текстовом редакторе GEdit с графическим интерфейсом.
- Если вы используете KDE Window Manager, вместо gksudo вводите команду kdesudo .
- Введите команду sudo passwd root . Этим вы создадите пароль для root, тем самым «включите» административный доступ. Смотрите, не забудьте этот пароль.
- Введите sudo -i . Введите пароль от root, когда это будет необходимо.
- Значок в терминале изменится с $ на # , указывая на то, что теперь вы обладаете правами суперпользователя.
Предоставьте доступ sudo другому пользователю. Если вы настраиваете учетную запись для того, кто в данный момент не имеет административного доступа, добавьте его имя в группу sudo. Для этого введите usermod -aG sudo username (замените «username» на правильное имя пользователя). [4] X Источник информации