Log in as root on linux

How to become root in Linux

root in linux

Computer Hope

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.

Читайте также:  Switch to tty linux

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.

Источник

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

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

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

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

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

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

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

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

Затем введите два раза пароль. После этого пользователь 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 тоже работали в таком режиме и поэтому они были очень уязвимы к вирусам.

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Похожие записи

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

Статья распространяется под лицензией Creative Commons ShareAlike 4.0 при копировании материала ссылка на источник обязательна .

Читайте также:  Linux посмотреть размер оперативной памяти

Об авторе

Основатель и администратор сайта losst.ru, увлекаюсь открытым программным обеспечением и операционной системой Linux. В качестве основной ОС сейчас использую Ubuntu. Кроме Linux, интересуюсь всем, что связано с информационными технологиями и современной наукой.

4 комментария к “Как зайти под root в Ubuntu”

Ну а что там с другими DE? Решение я знаю, но почему их нет в статье? Огласите весь список, пожалуйста! Ответить

Поставил два дня назад Ubuntu, просто посмотреть что за зверь такой Linux. Посмотрел. Теперь понял почему Windows рулит в мире, а Linux в глубокой попе ) Если после установки в Windows сразу можно работать (копировать, вставлять файлы, создавать папки редактировать и тд), то в Linux НИЧЕГО нельзя делать. То есть вообще ничего. Разве что браузер работает и можно что то посмотреть. А для того чтобы получить разрешение на работу в Linux, надо сначала выучить команды терминала ) Окститесь линуксоиды! Какой идиот сейчас будет заморачиваться с командами? Современная молодежь даже не знает что такое терминал. Почитал заклинания линуксоидов: какие страшные картинки рисуют, если юзер зашел под root. Чуть ли не конец света ) Как будто в Windows нет важных файлов, а все важнейшие для юзера файлы только в Linux ) Вы вообще про переустановку системы слышали? Если нет, сообщаю: Linux гораздо проще переустановить, чем Windows, не надо активировать систему. Так что заходим под root, спокойно что то ломаем и спокойно переустанавливаем. Никакой трагедии. По крайней мере такая дикая защита от ЮЗЕРА не нужна. Ответить

Источник

How to log into your Linux Server as a root user?

How to log into your Linux Server as a root user?

On Linux operating systems, the root user act as a superuser. The root account has root privileges. What this means is that it can read and write any files on the system, perform operations as any user, change system configuration, install and remove software, and upgrade the operating system and/or firmware. In essence, it can do pretty much anything on the system.
Here at LinuxAPT, as part of our Server Management Services , we regularly help our Customers to perform Software Installation tasks on their server.
In this context, we shall look into how to run commands as root user using nonuser, su, and sudo utilities.

More about Root user on Linux?

Root user is the conventional name of the user who has all rights or permissions on the system. The root user can do many things an ordinary user cannot, such as changing the ownership of files, mounting disk, formatting & restating new file system, starting/stopping services, and binding to ports numbered below 1024 and any other tasks.
Basically, it is not a good practice for anyone to use root as their normal user account, because of security risks. Therefore, you use a normal user account instead. You need to use the su or sudo command to switch to root user account.

Here we will look into some commands which root user enjoys.

1. su command.

The su command is use to change user ID or become super-user during a login session i.e. it allows you to become a super user or substitute user, spoof user, set user or switch user.

Читайте также:  Broadcom drivers linux ubuntu

Note: su only works if you know the target or root user’s password.

What is the su command syntax?

If used without a user-name, su defaults to becoming the super user. The user will be prompted for a password accordingly.
To log in as root user type the following command (you need to supply root user account password when prompted):

You will get an output such as;

Once logged in, your prompt should change from $ to # . To log in as another user say linuxapt, run the following command (you need to supply linuxapt user account password when prompted):

You will get an output such as this;

2. How to establish Remote root login over the ssh session?

Now with an ssh client tool such as putty, you can run the following command;

$ ssh root@server.ip-address-here
$ ssh root@server1.linuxapt.com

In some cases, the remote root login over ssh session is disabled in most cases for security reasons.
Start by logging in as a normal user and then switch to root account using the su command as shown below;
## login as a normal user ##

ssh user1@server1.linuxapt.com

## now switch to root account ##

3. More about su command and log files?

The su command logs its usage in a system log file. This is useful to find out su login information.
If you are RHEL / CentOS / Fedora Linux user type the following as root to see the contents of » /var/log/secure «, execute the command:

For Debian / Ubuntu Linux user, execute:

4. More about sudo command?

The sudo is a program for Linux operating systems that allows users to run programs with the security privileges of another user, normally the superuser (root). By default, sudo will prompt for a user password but it may be configured to require the root password or no password at all. Ubuntu Linux and many other Operating system uses sudo command for many administrative tasks.
sudo executes a command as another user but follows a set of rules about which users can execute which commands as which other users. This is configured in a filed named /etc/sudoers . Unlike su, sudo authenticates users against their own password rather than that of the target user. See how to configure and use sudo tool under Linux operating system.

For instance, to login as root under Linux, execute the command:

Then your will be prompted to enter a password. Once you enter the password, you will be logged in as the root and you will be able to enjoy sudo privileges.

5. How to work with Sudo and log file?

The sudo log can be viewed by issuing the following command as root user:

## Generic file for Unix/Linux ##

[Need urgent support to install any Software on your CentOS Server? Our Server Administrator will help you today.]

Conclusion

This article will guide you on how to run commands as root user using nonuser, su, and sudo utilities.

Источник

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