- We can help you
- Logging in as root
- Running commands as root without the root password
- Что такое sudo
- We can help you
- 1. su command.
- What is the su command syntax?
- 2. How to establish Remote root login over the ssh session?
- 3. More about su command and log files?
- 4. More about sudo command?
- 5. How to work with Sudo and log file?
- Содержание
- login as root in Ubuntu desktop GUI
- error found when loading root
- Содержание
- 1: How to enable Ubuntu root Login Temporarily?
- 2: How to enable root user in ubuntu via Graphical User Interface?
- 3: How to enable ubuntu root in Command-line?
- Conclusion
- How to change Ubuntu root password?
- How to change the Ubuntu default password using the command line?
- How to change default root password Ubuntu using GUI?
- How to reset the default ubuntu password ?
- How to reset Ubuntu’s root password from Recovery Mode
- How to switch a root user account in Ubuntu
- Sudo Users
- What are Ubuntu default login credentials?
- What is the Ubuntu Default Root Password?
- How to enable root account in Ubuntu?
- How to disable your root user account in Ubuntu?
- Advantages and Disadvantages of Ubuntu
- Conclusion
- What is a Root user?
- About the Article
- Использование sudo
- Время действия введённого пароля
- Где используется sudo
- Получение прав суперпользователя для выполнения нескольких команд
- How to change the root password (An alternative approach)?
- Ссылки
- Get Temporary root access through the sudo command
- Unlock/lock root account
- Настройка sudo и прав доступа на выполнение различных команд
- Разрешение пользователю выполнять команду без ввода пароля
- Создание синонимов (alias`ов)
- Запуск программ с правами администратора в терминале
- Когда нужно работать под пользователем root?
- Sudo не спрашивает пароль
- Запуск графических программ с правами администратора
- Использование традиционного root аккаунта и команды su
- Ubuntu 11.04 и младше
- Ubuntu 11.10 и старше
- Using command sudo –i
- Using Command sudo –s
- Using Command sudo su –
- Using Command su – root
- Using Command su –
Run the command mentioned below to enable the account:
$ sudo -iThe password can then be updated using either the «sudo passwd root» or «» command.
$ sudo -s$ sudo su -$ sudo - root$ sudo -After enabling the account using the above command, the password can be updated using either the «sudo passwd root» or «» command.
We can help you
Updated: by

Logging in as root
su
Or, you can use the whoami command to determine the account you are using.
When logging in as root, it is often useful to use a single dash after the su command, like this:
su -
Running commands as root without the root password
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.
Что такое sudo
sudo — это утилита, предоставляющая привилегии root для выполнения административных операций в соответствии со своими настройками. Она позволяет легко контролировать доступ к важным приложениям в системе. По умолчанию, при установке Ubuntu первому пользователю (тому, который создаётся во время установки) предоставляются полные права на использование sudo. Т.е. фактически первый пользователь обладает той же свободой действий, что и root. Однако такое поведение sudo легко изменить, об этом см. ниже в пункте про настройку sudo.
Here at , as part of our Server Management Services, we regularly help our Customers to perform related Linux System queries.
Run the below command:
$ sudo passwd rootOutput
Enter new UNIX password:
Retype new UNIX password:
passwd: password updated successfullyIt’s strongly recommend that you set strong and unique password. It is a most important security aspect of your system. Your password should have at least 14 characters and contains one uppercase letter, one lowercase letter, one number, and one special character.
Finally, you have successfully enabled the root account by setting up password.
$ sudo passwd -l rootWe can help you

SSH root login is disabled by default in Ubuntu 18.04. SSH server for Ubuntu provides by the openssh-server package and root login is controlled by the PermitRootLogin directive in the OpenSSH server configuration (sshd_config file):
grep -i "rootlogin" /etc/ssh/sshd_configRoot login is disabled, if the PermitRootLogin directive is commented out (# in front) or its value is not set to yes.

- Open the /etc/ssh/sshd_config:
vim /etc/ssh/sshd_config - Uncomment the line PermitRootLogin and set the value to yes:
PermitRootLogin yes - To make the new setting take effect, restart the ssh server:
systemctl restart sshd.service
ssh [email protected]Next: Change Ubuntu SSH Port
This guide will help you out.
1. su command.
What is the su command syntax?
The syntax is:
$ su -You will get an output such as;
$ su - linuxaptYou will get an output such as this;
2. How to establish Remote root login over the ssh session?
## now switch to root account ##
3. More about su command and log files?
tail -f /var/log/securetail -f /var/log/auth.log4. More about sudo command?
For instance, to login as root under Linux, execute the command:
$ sudo -sThen 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?
## Generic file for Unix/Linux ##
tail -f /var/log/messages## Debian/Ubuntu ##
tail -f /var/log/auth.log## RHEL/CentOS/SL/Fedora Linux ##
tail -f /var/log/auth.logСодержание
Для начала определимся в терминах:
root — суперпользователь системы. А если более точно, то это пользователь с идентификатором 0. Имя здесь не особо важно. Хотя по умолчанию это общее имя пользователя с нулевым идентификатором пользователя для всех unix-like операционных систем. Это пользователь обладает наивысшими привилегиями в ОС.
sudo — консольная команда выполняющая команду переданную ей как аргумент с правами суперпользователя (root). Графический аналог — gksu, kdesu.
# — символ подсказки в консоли, который явно указывает, что команда будет выполнена под учетной записью root (в отличии от символа $, который говорит что команда будет выполнена от имени обычного пользователя).
We can enable Ubuntu root account by giving it a password by using the passwd command. But to run passwd command on the root account, you need to have sudo privileges.
groups
sudo passwd rootFirst, the command will prompt for your own password to confirm that you have sudo privileges.
After you’ve entered your password, the passwd command will prompts you to enter a new password for the root account (Twice).

su -login as root in Ubuntu desktop GUI
[security]
AllowRoot=trueauth required pam_succeed_if.so user != root quiet_successAnd comment out the line (put # in front):
#auth required pam_succeed_if.so user != root quiet_successAfter that restart your computer, when you come back to the login screen, click on the “not listed?”.

error found when loading root

To fix this error open the root profile in a text editor:
gedit /root/.profilemesg n || trueif `tty -s`; then mesg n
fiСодержание
В любой Linux-системе обязательно есть один привилегированный пользователь — root. Этот пользователь имеет права на выполнение любых действий, удаление любых файлов и изменение любых параметров. Как-то ограничить свободу действий root практически невозможно. С другой стороны, все остальные пользователи системы обычно не имеют большинства необходимых прав, например, прав на установку программ, поскольку это является административной операцией, права на которую есть только у root. Ещё одной распространённой операцией, доступной только суперпользователю, является копирование и изменение файлов в системных папках, куда обычный пользователь доступа не имеет.
Раньше данная проблема решалась достаточно просто: при обладании паролем root можно было зайти в систему под его аккаунтом либо временно получить его права, используя команду su. Потом выполнить все необходимые операции и вернуться обратно под обычного пользователя. В принципе, такая схема работает неплохо, однако у неё есть много существенных недостатков, в частности, невозможно никак (точнее, очень сложно) ограничивать административные привилегии только определённым кругом задач.
Поэтому в современных дистрибутивах Linux вместо root аккаунта для администрирования используется утилита sudo.
В Ubuntu по умолчанию root аккаунт вообще отключён, т.е. вы никаким способом не сможете попасть под root, не включив его. root именно что отключён, т.е. он присутствует в системе, под него всего лишь нельзя зайти. Если вы хотите вернуть возможность использовать root, смотрите ниже пункт о включении root аккаунта.
![How to Enable Root Account in Ubuntu? [Ubuntu Root Login]](https://monovm.com/wp-content/uploads/2021/05/cover849-main.webp)
List of content you will read in this article:
If you are a newbie, you may be scratching your head about how to enable your root account in Ubuntu! Well, for several security purposes, the ubuntu root login account is kept disabled. Before we begin, here is some preface.
When you install Ubuntu, a root account is created. The issue here is that you do not have the provision to set the password for the account.
sudo grep root /etc/passwd

The x in the output signifies that the account’s password is empty.
sudo grep root /etc/shadow

- Temporary Method
- Command-Line and Graphical User Interface Method
- Command-Line Method
1: How to enable Ubuntu root Login Temporarily?


2: How to enable root user in ubuntu via Graphical User Interface?
Type root in the first textbox.

Type your root account password.

As soon as you type the password, you encounter an error message. The reason is that a security layer in the graphical interface stops any login until and unless several other configuration files are configured.
sudo cp /etc/gdm3/custom.conf /etc/gdm3/custom.conf_backup
sudo cp /etc/pam.d/gdm-password /etc/pam.d/gdm-password_backup

Now, simply, open the “/etc/gdm3/custom.conf” configuration file
sudo vi /etc/gdm3/custom.conf


Press save and exit.
Now, open “/etc/pam.d/gdm-password” which is a configuration file.


Just save and hit exit on the ‘gdm’ configuration file.
sudo reboot -f
As you have rebooted your system, login into the root account now.

You can log in to the root account easily.
sudo passwd -dl root

Reverse whatever changes you made in the two configuration files earlier.
Delete “AllowRoot=true” from the “/etc/gdm3/custom.conf” configuration file as shown below.

Next, delete the ‘#’ from “/etc/pam.d/gdm-password”.

And you are done!
3: How to enable ubuntu root in Command-line?
Using the command-line method, you can easily enable or disable the root account through the command line. Here, you cannot log in through a graphical interface.
sudo -i passwd root

su – root

sudo passwd -dl root

To be sure, switch to the root account and see if the process is successful.
su - root

If you see the same message as the above image, then yes, you have successfully disabled the account, as now you can see that the authentication has failed.
Conclusion
We hope that the article solved your queries and provided you with a better understanding of the topic. If you have any questions or suggestions, please leave them in the comment section below.
People are also reading:
![Ubuntu Default Root Password? [Change Ubuntu Password]](https://monovm.com/wp-content/uploads/2021/09/cover451-main.webp)
List of content you will read in this article:
How to change Ubuntu root password?
- Open the terminal by pressing Ctrl+Alt+T or searching for «Terminal» in the Ubuntu Dash.
- Type the command «sudo passwd root» and press Enter. You will be prompted to enter your current user password.
- After authenticating, you can set a new password for the root user. Make sure to choose a strong and secure password.
- Retype the new password when prompted to confirm.
- Once the password change is successful, you can exit the terminal.
How to change the Ubuntu default password using the command line?
- Launch the terminal by pressing Ctrl+Alt+T or searching for «Terminal» in the applications menu.
- To change the root password, you need administrative privileges. Execute the following command to access root privileges: sudo -i
- Once you have root privileges, enter the following command to change the root password: passwd
You will be prompted to enter a new password. Make sure to choose a strong and secure password that includes a combination of uppercase and lowercase letters, numbers, and special characters. Note that the password will not be visible as you type.
- After entering the new password, you will be prompted to confirm it. Re-enter the password carefully, ensuring it matches exactly as you intended.
- If the password change is successful, you will receive a confirmation message. Your Ubuntu system’s root password is now updated.
Remember to keep your root password confidential and avoid using easily guessable information. Regularly changing your passwords enhances the overall security of your Ubuntu system.
How to change default root password Ubuntu using GUI?
- Launch the Terminal: Open the Terminal by clicking on the Applications menu, typing «Terminal» in the search bar, and selecting the Terminal application.
- Access User Accounts: Type «sudo gnome-control-center user-accounts» command in the Terminal and press Enter. This command will open the User Accounts settings.
- Authenticate: Enter your user password when prompted to authenticate your access.
- Modify Root Account: In the User Accounts settings, select the » root » account and click the «Password» button.
- Set New Password: Enter the new password for the root account in the provided fields. Make sure to choose a strong and secure password.
- Apply Changes: Click on the «Change» or «Apply» button to save your changes to the root password.
- Confirm Changes: Close the User Accounts settings and log out of your session. To apply the new root password, you need to log back in using the updated credentials.
Remember, changing the root password in Ubuntu enhances the overall security of your system by preventing unauthorized access. Ensure you choose a unique and robust password to maintain the integrity of your Ubuntu installation.
How to reset the default ubuntu password?
Forgot your Ubuntu login password? If you haven’t used Ubuntu for a long time, and now you want to login in, and you don’t remember your password. So here is the method to reset your Ubuntu Password. You quickly get your password, and you don’t even need to reinstall it.
How to reset or change root password:
Open up the terminal!
After opening the terminal, type the command sudo space passwd space root
- [ Sudo passwd root ] & press enter
- Enter the new root password and press Enter button
- Retype root password and enter
- Password changed successfully
To verify your new password, use this command.
- su root & press Enter key
- Now Enter the new given password of your Ubuntu and press Enter Key
Now you can use your new Ubuntu Root Password. You have successfully made a new password to the Ubuntu root terminal.
How to reset Ubuntu’s root password from Recovery Mode
- Start or restart your Ubuntu system.
- When the GRUB boot menu appears, select the advanced options for Ubuntu and choose the recovery mode option. If you don’t see the GRUB boot menu, you may need to press and hold the Shift key during startup to make it appear.
- In the recovery mode menu, select the option that says «root Drop to root shell prompt.» This will drop you into a root shell with root privileges.
- Remount the file system in read/write mode by running the following command:
mount -o remount,rw /
- Next, you need to change the root password. Use the following command to set a new password:
You will be prompted to enter the new password twice. Note that when you type the password, it won’t be visible on the screen for security reasons. Press Enter once you’ve entered the new password.
- After setting the new password, you can reboot your system by running:
Remember to keep the root password secure and make sure to remember it or store it in a safe place.
How to switch a root user account in Ubuntu
Sudo Users
The first time you use Sudo, you will be prompted to enter the password. If you want to run the command with sudo without entering the password, you must edit the sudoers file.
What are Ubuntu default login credentials?
What is the Ubuntu Default Root Password?
How to enable root account in Ubuntu?
1. Open a terminal: Press `Ctrl + Alt + T` on your keyboard to open a terminal window.
sudo passwd root
4. Next, you will be asked to enter the new password for the root account. Type your desired password and press Enter. Please note that while typing the password, no characters will be displayed on the screen for security reasons.
5. Confirm the new password by typing it again and pressing Enter.
How to disable your root user account in Ubuntu?
- Open a terminal on your Ubuntu system.
- Run the following command to set a password for the root account (if you haven’t already done so): sudo passwd root
You will be prompted to enter and confirm a new password for the root account.
- Once the root password is set, run the following command to lock the root account: sudo passwd -l root
This command locks the root account, effectively disabling it.
Advantages and Disadvantages of Ubuntu
Here you can find the pros and cons of using Ubuntu leaving root logins disabled by default, includes:
- People often forget their login passwords occasionally (the root password).
- It avoids the access of «I can do anything» login by default. It will prompt for a password earlier; the changes can happen!
- Sudo adds a log access of the command(s) run (in /var/log/auth.log). In case you were in trouble, you can go to the authorities and run.
- Every cracker trying to brute-force their manner in on a server will know it has an account named root and could try that first.
- What they do not know is the usernames of your other users. Due to the fact that the root account password is locked, this attack doesn’t pose any threat at all as there may be no password to crack or guess inside the first location.
- Allows easy transfer of admin rights by adding or removing users. When you use only one Ubuntu root password, you could change the root password if you forgot.
- Sudo may be set up with a safety policy.
Automatically the authentication expires after some time (you can also set the time duration). So if you walk away or leave your desktop a few times from the terminal after running commands as root using sudo, you will not be leaving a root terminal open indefinitely.
Conclusion
You can also add special characters to your password. Add up to at least 16 characters with upper, and lowercase letters and numbers. It is how we can change the default root password.
What is a Root user?
About the Article
$ su -

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.

You can read later in the article about how to lock/unlock the root account.
sudo -s
Let us explain this with an example.
$ nano /etc/adduser.conf

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.

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.
# exit

Использование sudo
Есть несколько важных трюков в использовании sudo:
Будьте внимательны выполняя команды с sudo или работая в сессии root-а (и не забывайте выйти из сессии root-а по окончанию действий требующих расширенных прав).
Не пользуйтесь sudo там, где это не нужно.
Время действия введённого пароля
Возможно, вы хотите изменить промежуток времени, в течение которого sudo действует без ввода пароля. Этого легко добиться добавив в /etc/sudoers (visudo) примерно следующее:
Defaults:foo timestamp_timeout=20
Здесь sudo для пользователя foo действует без необходимости ввода пароля в течение 20 минут.
Если вы хотите, чтобы sudo всегда требовал ввода пароля, сделайте timestamp_timeout равным 0.
Где используется sudo
sudo используется всегда, когда вы запускаете что-то из меню Администрирования системы. Например, при запуске Synaptic вас попросят ввести свой пароль. Synaptic — это программа управления установленным ПО, поэтому для её запуска нужны права администратора, которые вы и получаете через sudo вводя свой пароль.
Однако не все программы, требующие административных привилегий, автоматически запускаются через sudo. Обычно запускать программы с правами администратора приходится вручную.
Получение прав суперпользователя для выполнения нескольких команд
Иногда возникает необходимость выполнить подряд несколько команд с правами администратора. В этом случае можно временно стать суперпользователем одной из следующих команд:
sudo -s sudo -i
После этого вы перейдёте в режим суперпользователя (с ограничениями, наложенными через настройки sudo), о чём говорит символ # в конце приглашения командной строки. Данные команды по действию похожа на su, однако:
— sudo -s — не меняет домашний каталог на /root, домашним остается домашний каталог пользователя вызвавшего sudo -s, что обычно очень удобно.
— sudo -i — сменит так же и домашний каталог на /root.
Для выхода обратно в режим обычного пользователя наберите exit или просто нажмите Ctrl+D.
How to change the root password (An alternative approach)?
$ sudo -i
The system will prompt you to enter the current sudo password. Please enter the password and hit Enter.

$ passwd

Ссылки
Настройка sudo — топик на форуме о времени действия пароля
Get Temporary root access through the sudo command
$ sudo nano adduser.conf
Unlock/lock root account

$ sudo passwd root

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.
$ sudo passwd -dl root

Настройка sudo и прав доступа на выполнение различных команд
sudo позволяет разрешать или запрещать пользователям выполнение конкретного набора программ. Все настройки, связанные с правами доступа, хранятся в файле /etc/sudoers. Это не совсем обычный файл. Для его редактирования необходимо (в целях безопасности) использовать команду
sudo visudo
%admin ALL=(ALL) ALL
Подробнее о синтаксисе и возможностях настройки этого файла можно почитать выполнив
man sudoers
Если вы допустите ошибку при редактировании этого файла, то вполне возможно полностью лишитесь доступа к административным функциям. Если такое случилось, то необходимо загрузиться в recovery mode, при этом вы автоматически получите права администратора и сможете всё исправить. Кроме того, отредактировать этот файл можно с LiveCD.
Разрешение пользователю выполнять команду без ввода пароля
Для того, что бы система не запрашивала пароль при определенных командах необходимо в sudoers после строки # Cmnd alias specification добавить строку, где через запятую перечислить желаемые команды с полным путём(путь команды можно узнать, выполнив which имя_команды:
# Cmnd alias specification Cmnd_Alias SHUTDOWN_CMDS = /sbin/shutdown, /usr/sbin/pm-hibernate, /sbin/reboot
И в конец файла дописать строку
имя_пользователя ALL=(ALL) NOPASSWD: SHUTDOWN_CMDS
Внимание! Вышеописанные действия не отменяют необходимости ввода команды sudo перед вашей командой
Создание синонимов (alias`ов)
Для того, чтобы не только не вводить пароль для sudo, но и вообще не вводить sudo, сделайте следующее:
откройте файл .bashrc, находящейся в вашем домашнем каталоге
~bashrc
и добавьте в конец файла строки
= = pm-hibernate= = =
Запуск программ с правами администратора в терминале
Для запуска в терминале команды с правами администратора просто наберите перед ней sudo:
sudo <команда>
У вас попросят ввести ваш пароль. Будьте внимательны, пароль при вводе никак не отображается, это нормально и сделано в целях безопасности, просто вводите до конца и нажимайте Enter. После ввода пароля указанная команда исполнится от имени root.
Система какое-то время помнит введённый пароль (сохраняет открытой sudo-сессию). Поэтому при последующих выполнениях sudo ввод пароля может не потребоваться. Для гарантированного прекращения сессии sudo наберите в терминале
sudo -K
Кроме того, часто встречаются ошибки, связанные с каналами в Linux. При исполнении команды
sudo cat test.txt | grep text > result.txt
с правами root исполнится только cat, поэтому файл result.txt может не записаться. Нужно либо писать sudo перед каждой командой, либо временно переходить под суперпользователя.
Когда нужно работать под пользователем root?
Все это однако не означает что никаких административных действий выполнить в такой системе нельзя. Для исполнения административных команд используется команда sudo (или её графический аналог gksu).
Sudo не спрашивает пароль
sudo без пароля — чудовищная дыра в безопасности, кому попало разрешено делать что угодно. Если вы разрешили это намеренно — срочно верните обратно как было.
Однако, в некоторых случаях sudo внезапно перестаёт требовать пароль само по себе. Если сделать visudo, то можно увидеть примерно такую строку, которую пользователь вроде бы не добавлял:
ALL ALL=(ALL) NOPASSWD:ALL
Скорее всего, эта катастрофичная строка была добавлена при установке программы типа Connect Manager от МТС или Мегафона. В таком случае, её нужно поменять на строку, разрешающую с правами root запускать только этот Connect Manager, примерно так:
юзернейм ALL= NOPASSWD: /путь/к/программе
Есть и другие варианты решения проблемы, небольшое обсуждение здесь.
Запуск графических программ с правами администратора
Для запуска графических программ с правами администратора можно воспользоваться диалогом запуска программ, вызываемым по умолчанию сочетанием клавиш Alt+F2.
Допустим, нам необходимо запустить файловый менеджер Nautilus с правами администратора, чтобы через графический интерфейс как-то изменить содержимое системных папок. Для этого необходимо ввести в диалог запуска приложений команду
gksudo nautilus
Вместо gksudo можно подставить gksu, кроме того, пользователи KDE должны вместо gksudo писать kdesu. У вас попросят ввести свой пароль, и, если вы обладаете нужными правами, Nautilus запуститься от имени администратора. Запуск любого графического ПО можно производить с правами администратора, просто написав в диалоге запуска
gksudo <имя_команды>
Будьте предельно внимательны при работе в приложениях, запущенных с правами администратора. Вы безо всяких предупреждений со стороны системы сможете выполнить любую операцию, в частности, удалить системные файлы, сделав при этом систему неработоспособной.
Использование традиционного root аккаунта и команды su
Разблокировка учетной записи root приводит неоправданным рискам (работая постоянно под рутом вы имеете 100500 способов «отстрелить себе ногу»), а также упрощает получение доступа к вашему компьютеру злоумышленником.
Ubuntu 11.04 и младше
Для входа под root достаточно задать ему пароль:
sudo passwd root
Ubuntu 11.10 и старше
Начиная с версии 11.10 был установлен менеджер входа lightdm, и дело со входом под root обстоит немного сложнее.
1. Устанавливаем root пароль.
Введите в терминал:
sudo passwd root
gksu gedit /etc/lightdm/lightdm.conf
В конце файла допишите:
greeter-show-manual-login=true
3. Перезагружаем lightdm.
Введите в терминал:
sudo service lightdm restart
Для обратной блокировки учетной записи root вам потребуется откатить изменения в настройках lightdm, а также заблокировать учетную запись root командой в терминале:
sudo passwd -l root






