You have to be root linux

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 allows you to 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.

Читайте также:  Windows обновление безопасности которое вылетает

If you need to add a user to the sudoers list, use the visudo command that requires root privileges to run, and allows you to safely edit the sensitive sudoers file.

Источник

How to become Root user in Ubuntu Command Line using su and sudo

What is a Root user?

Before starting with how to become a root user in order to perform sensitive Ubuntu operations, it is important to have some understanding of the significance of a root user in Linux. The latest versions of Ubuntu, by default, do not come with a root user with a specially encrypted password; it has hence created a functionality by the name of “sudo” which you can use to perform various administrative operations. You can either temporarily become root user or you need to provide a password with the sudo command that helps in keeping accountability for all actions of the user as an administrator. By default, the first user created when you install Ubuntu is given the sudo rights. Ubuntu gives it complete root privileges and it is added to the list of sudoers in the /etc/sudoers file. It is important to note that you need to be an authorized sudoer to perform all the root user operations described in this article.

About the Article

In this article, we will explain how to become a root user in the Ubuntu command line. This will help you in performing all the software installation, removal, customization, and also system configuration operations. We have run the commands and procedures mentioned in this article on a Ubuntu 18.04 LTS system. We will be using the Ubuntu command line, the Terminal, in order explain how to become and also how to change the password for root user. Therefore, you need to open the Terminal application either through the system Dash or the Ctrl+Alt+T shortcut.

How to become root?

Open your Ubuntu Terminal and enter the following command:

This command will ask the system to log you in as a superuser.

The system will ask you the password for root. Enter the password and hit Enter.

Ideally, you now will be able to see the “#” sign in front of your command prompt. This would mean that you are now logged in as root.

In case you get the following authentication failure message when you enter the password for root, it means that the root account is blocked at the moment.

You can read later in the article about how to lock/unlock the root account.

To become root user from an unprivileged (normal user account) account when there is no root password set, use this command:

Enter the password of your Ubuntu user when requested. Only Ubuntu users that are members of the sudo group are able to become root user like this. The user that is created during Ubuntu installation is a member of the sudo group by default.

Now that you are logged in as root, you can perform all the administrative operations on Ubuntu. Advertisement

Let us explain this with an example.

The file adduser.conf located in /etc/ needs root privileges for you to make any changes to it. When we open it as a normal user, you will be able to see the following lines at the end of the file:

“File ‘adduser.conf; is unwritable’

The system file is mentioned as unwritable because an unauthorized user can not make any changes to its configurations.

You can only edit it if you are logged in as root or if you are using the sudo command to temporarily avail root privileges.

Since we are now logged in as root, we will be able to see the file in the following manner:

Читайте также:  Tcp keepalives idle windows

We can make any changes to the file and save the changes by hitting Ctrl+X.

Note: It is very important to stay careful while making any sensitive changes to your system files while logged in as root. Any undue change to the system files can mess up with your entire system settings.

You can exit the root command prompt and become a normal user again by using the exit command as follows:

Get Temporary root access through the sudo command

Instead of logging in as a root in the command line and getting on to the # (root user) command prompt, you can use the sudo command with your other commands to temporarily become root.

For example, we can open the same adduser.conf file that we mentioned before in an editable format by availing the root rights as follows:

This is especially useful because any authorized user(the one added in the sudoers list) can enter their own password and temporarily gain root access for running a few commands. Another benefit of using this command is that you can perform tasks that require root privileges even when the root account is in a blocked state.

Unlock/lock root account

When you get the following message when logging in as root, it is most probably because the root account is locked. Most Ubuntu systems have this account locked by default.

You can, however, unlock it by entering the following command as sudo:

The system will ask you to enter a new UNIX password twice. After that, it will update the root password and the account will be unlocked.

After you are done with performing your root operations, you can lock the root account again by entering the following command:

How to change the root password (An alternative approach)?

Apart from the method we just described above to change the root password, you can use the following alternative method:

Only a root user can change his/her own password. Therefore you need to login as root first. Enter the following command to do so:

The system will prompt you to enter the current sudo password. Please enter the password and hit Enter.

Now that you are logged in as root, you can change the passwd for the current (root) user by using the passwd command as follows:

After working along with this article, you are now capable of becoming root on your Ubuntu command line. You are now free to perform all the operations that only an extremely privileged user is entitled to perform. But be very careful as Uncle Ben would say, With great power comes great responsibility!

Karim Buzdar

About the Author: Karim Buzdar holds a degree in telecommunication engineering and holds several sysadmin certifications. As an IT engineer and technical author, he writes for various web sites. You can reach Karim on LinkedIn

Источник

🐧 Как стать пользователем root на Linux

Пользователь root – это суперпользователь Linux, который похож на администратора на Windows.

Он может выполнить все виды административных операций, поэтому никому не предоставляйте root-права, поскольку они могут повредить вашу систему, если они не знакомы с Linux.

Отключение root является безопасным подходом, в UBUNTU как правило это реализовано и предоставляется пользователь sudo вместо root-доступа.

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

Если вы не знаете, как настроить доступ sudo в Linux, обратитесь к следующей статье.

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

Система записывает все в журнал сообщений (/var/log/message).

1) Как стать пользователем root на Linux с помощью команды su

Команда su (сокращение от «substitute» или « switch user» или «super user») позволяет вам запускать команды с привилегиями другого пользователя, по умолчанию пользователь root.

Читайте также:  Лучшие иконки для рабочего стола windows 10

su – самый простой способ переключиться на учетную запись root в Linux, но для использования команды su в Linux вы должны знать пароль root.

Это позволит вам получить домашний каталог пользователя root и его оболочку.

Когда вы вошли в систему от пользователя root, командная строка заканчивается # вместо $.

Вы можете задаться вопросом, почему я должен использовать «-» при использовании команды su, и в чем разница.

  • su -: когда вы используете «su -», система устанавливает целевую пользовательскую среду, включая HOME, SHELL, USER, LOGNAME и PATH.
  • su: Сохраняет текущую пользовательскую среду.

2) Как стать пользователем root на Linux с помощью команды «sudo -i»

Команда sudo (сокращение от super user do) позволяет временно запускать другие команды от имени пользователя root.

Это лучший способ выполнять команды от пользователя root, потому что система записывает все, что вы делаете с помощью команды sudo.

Пользователю не нужно знать пароль пользователя root, чтобы стать пользователем root.

Вместо этого пользователи будут вводить свой собственный пароль, чтобы получить временный root-доступ.

Система предоставит вам интерактивную рут оболочку, и вы попадете в домашний каталог рута (/root).

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

3) Как стать пользователем root на Linux с помощью команды «sudo -s»

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

Источник

Как зайти под root в Ubuntu

Политика дистрибутива Ubuntu нацелена на то, что все действия, требующих административных привилегий надо выполнять с помощью команды sudo. Использовать root пользователя как основного для новичков опасно, поскольку они ещё плохо ориентируются в системе и могут забыть, что они вошли как root и удалить что-то важное.

А поскольку восстановить файлы, удалённые с помощью команды rm почти нельзя, то лучше новичков туда не пускать. Но иногда возникает необходимость войти под пользователем root. В этой небольшой статье мы рассмотрим как это сделать.

Как зайти под root в Ubuntu

По причинам, описанным выше для пользователя root пароль в Ubuntu не задан по умолчанию, поэтому вы не можете просто так войти от его имени с помощью в виртуальных консолях доступных по Ctrl+Alt+FN или с помощью утилиты su. Поскольку пароля нет, ввести его верно вы не сможете.

Но это всё очень просто обходится. Для того чтобы войти под пользователем root в терминале достаточно дописать sudo перед командой su:

Также можно использовать опцию -i команды sudo чтобы открыть консоль от имени суперпользователя:

Однако, если вы хотите авторизоваться от имени этого пользователя в виртуальной консоли или по SSH, то вам надо сначала задать для него пароль. Для этого выполните:

sudo passwd root

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

Но если вам всё же очень хочется, надо немного настроить правила PAM для GDM. Для этого откройте файл /etc/pam.d/gdm-password и закомментируйте там строчку:

sudo vi /etc/pam.d/gdm-password

# auth required pam_succeed_if.so user != root quiet_success

После этого вы сможете авторизоваться от имени root в менеджере входа. Просто кликните по пункту Нет в списке, а затем введите логин root:

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

Это очень небезопасно, потому что любая программа может делать с вашим компьютером всё, что захочет и никто её не остановит. Фактически, первые версии Windows тоже работали в таком режиме и поэтому они были очень уязвимы к вирусам.

Источник

Оцените статью