How to Change Root Password on Ubuntu 20.04

Note: For help with configuring sudo privileges via its configuration file /etc/sudoers, please see Sudoers.

Warning: Directly logging in as root is like playing with fire, because one little typo is enough to lose critical data or make your system unbootable. Note that desktop environments will also function incorrectly if you login to them as root.

See these questions for the reasons behind why sudo is preferred and why root-login is disabled by default:

You may have noticed that you can’t log in as root on Ubuntu, this is because root doesn’t actually have a password set.

passwd: password updated successfully

And you will be prompted for the root password you’ve set. That’s it!

I’ve answered a similar question before.

While you can create a password for the root account allowing you to log in as root with su, there are some distinct benefits to using sudo.

sudo apt-get dist-upgrade

By default, sudo will ask you for your own account password when performing this. This helps security. This is remembered for a few minutes so if you have a few tasks to do with sudo it will only ask you for your password on the first.

You will see the above usage of sudo pretty much anywhere you read a tutorial about Ubuntu on the web. It’s an alternative to doing this.

Not having a root password makes brute force attacks on the root account impossible: this is relevant if you allow login over SSH. Instead, an attacker would need to know a local account name.

Getting a root shell

And similarly, instead of su — for a login shell you can use sudo su — or even sudo -i.

I am trying to change root password in my Ubuntu system.

This is what I did:

How do I change root password in Ubuntu?

asked May 13, 2013 at 18:26

Usually there is no need to set a root password. See: https://help.ubuntu.com/community/RootSudo

To set or change your (root) password:

To lock it again

sudo passwd -dl root

answered May 13, 2013 at 20:24

19 gold badges192 silver badges283 bronze badges

When you use sudo your already accessing root you don’t have to specify root.

If your trying to do this from recovery root you should:

mount -rw -o remount /
passwd

20 gold badges198 silver badges264 bronze badges

answered Nov 15, 2013 at 5:34

2 silver badges11 bronze badges

If ‘ashot’ is your root account, don’t call ‘sudo passwd’. I’ve been doing that for the past few months and it wouldn’t change my password.

To change my password, I had to call ‘passwd’ without ‘sudo’. Otherwise, the password modification is not taken account of.

answered Mar 23, 2015 at 22:01

passwd: Authentication token manipulation error
passwd: password unchanged

Try this steps;

Дополнительно:  Как исправить ошибку 0x000000ed на windows

— restart ubuntu, open it recovery mode
— drop root
— upgrade your ubuntu to a new version

This solved my problem, i hope it helps you too.

answered Aug 11, 2013 at 7:24

Possibly /etc/passwd and /etc/shadow don’t match.

Try to use command pwconv.

answered Nov 7, 2013 at 21:54

1 gold badge14 silver badges25 bronze badges

Provided by: passwd_4.2-3.1ubuntu5_amd64

НАЗВАНИЕ

passwd — изменяет пароль пользователя

СИНТАКСИС

Программа passwd изменяет пароли пользовательских учётных записей. Обычный пользователь
может изменить пароль только своей учётной записи, суперпользователь может изменить пароль
любой учётной записи. Программа passwd также изменяет информацию об учётной записи или
срок действия пароля.

Изменение пароля
Сначала пользователя попросят ввести старый пароль, если он был. Этот пароль
зашифровывается и сравнивается с имеющимся. У пользователя есть только одна попытка ввести
правильный пароль. Для суперпользователя этот шаг пропускается, для того чтобы можно было
изменить забытый пароль.

После ввода пароля проверяется информация об устаревании пароля, чтобы убедиться, что
пользователю разрешено изменять пароль в настоящий момент. Если нет, то passwd не
производит изменение пароля и завершает работу.

Затем пользователю предложат дважды ввести новый пароль. Значение второго ввода
сравнивается с первым и для изменения пароли из обеих попыток должны совпасть.

Затем пароль тестируется на сложность подбора. Согласно общим принципам, пароли должны
быть длиной от 6 до 8 символов и включать один или более символов каждого типа:

• строчные буквы

• цифры от 0 до 9

• знаки пунктуации

Не включайте системные символы стирания и удаления. Программа passwd не примет пароль,
который не имеет достаточной сложности.

Выбор пароля
Безопасность пароля зависит от стойкости алгоритма шифрования и размера пространства
ключа. В старых системах UNIX метод шифрования основывался на алгоритме NBS DES. Сейчас
рекомендуют более новые методы (смотрите ENCRYPT_METHOD). Размер пространства ключа
зависит от степени произвольности выбранного пароля.

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

О том, как выбрать стойкий пароль, читайте в
http://ru.wikipedia.org/wiki/Сложность_пароля.

ПАРАМЕТРЫ

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

Пользователи не могут изменять свои пароли в системе, если включён NIS и они не вошли на
сервер NIS.

Дополнительно:  Php-eval-console

Команда passwd для аутентификации пользователей и для смены паролей использует PAM.

ФАЙЛЫ

/etc/passwd
содержит информацию о пользователях

/etc/shadow
содержит защищаемую информацию о пользователях

/etc/pam.d/passwd
настройки PAM для passwd

ВОЗВРАЩАЕМЫЕ ЗНАЧЕНИЯ

Программа passwd завершая работу, возвращает следующие значения:

0
успешное выполнение

1
доступ запрещён

2
недопустимая комбинация параметров

3
неожиданная ошибка при работе, ничего не сделано

4
неожиданная ошибка при работе, отсутствует файл passwd

5
файл passwd занят другой программой, попробуйте ещё раз

6
недопустимое значение параметра

Where is root?

A strong password policy is one of the most important aspects of your security posture. Many successful security breaches involve simple brute force and dictionary attacks against weak passwords. If you intend to offer any form of remote access involving your local password system, make sure you adequately address minimum password complexity requirements, maximum password lifetimes, and frequent audits of your authentication systems.

Minimum Password Length

By default, Ubuntu requires a minimum password length of 6 characters, as well as some basic entropy checks. These values are controlled in the file /etc/pam.d/common-password, which is outlined below.

If you would like to adjust the minimum length to 8 characters, change the appropriate variable to min=8. The modification is outlined below.

Password Expiration

To enable the root account (i.e. set a password) use:

sudo passwd root

Use at your own risk!

Re-disabling your root account

First, restart your computer. If the GRUB menu doesn’t automatically appear for you every time while booting, hold the Shift key while booting. This will forcefully show the GRUB menu.

Next, mark the line Ubuntu from the menu and press e to edit the boot configuration.

We need to do the modification on the line starting with linux, which is the second last line in the configuration. Replace the last part quiet splash with rw init=/bin/bash.

Basically the change we are doing here is to login to a shell (init=/bin/bash) instead of GUI (quiet splash) with read and write (rw) privileges.

Press F10 to boot with this configuration. Note that this changed configuration is used only for that boot and is reset on the next boot.

Now, as done previously, we can run the command passwd here and reset the root password.

The root password has been changed. Now reboot the system normally and login as root with the new password.

Usage

As seen above, the prompt has now changed to root. Thus we are able to login to root using our own password.

Now, to change the root password, simply use the command passwd.

This will set the root password when used for first time, or change it to the new password when used afterwards.

Time to check if the new password works. Press Ctrl + D to exit root prompt. Then type command su to login as root, and enter the new root password which we just set.

Дополнительно:  Пропала Панель задач на Рабочем столе Windows 10: почему исчезла и как вернуть

In this way, we have successfully modified the root password and able to log in as root.

Logging in as another user

sudo -i -u amanda

The password being asked for is your own, not amanda’s.

Sudo

To use sudo on the command line, preface the command with sudo, as below: Example #1

sudo chown bob:bob /home/bob/*

sudo /etc/init.d/networking restart

To repeat the last command entered, except with sudo prepended to it, run:

Allowing other users to run sudo

In the terminal (for Precise Pangolin, 12.04), this would be:

In previous version of Ubuntu

Downsides of using sudo

Although for desktops the benefits of using sudo are great, there are possible issues which need to be noted:

Reset sudo timeout

You can make sure sudo asks for password next time by running:

Adding and Deleting Users

Please note that many websites and old threads advise the use of gksu. However, such search results are obsolete. gksudo has not been updated for years and is not even available in Bionic (18.04) and higher. gksu has been replaced by pkexec, but even pkexec is being deprecated by the mainline Ubuntu developers. They have taken the position that file manipulation and editing under root should be restricted to the command line.

Flavour-specific workarounds

There are a number of flavour-specific options for running graphical applications as root:

General workarounds

There are a number of benefits to Ubuntu leaving root logins disabled by default, including:

Special notes on sudo and shells

None of the methods below are suggested or supported by the designers of Ubuntu.

To start a root shell (i.e. a command window where you can run root commands), starting root’s environment and login scripts, use:

sudo -i (similar to sudo su — , gives you roots environment configuration)

To start a root shell, but keep the current shell’s environment, use:

sudo -s (similar to sudo su)

Summary of the differences found —

For a detailed description of the differences see man su and man sudo .

Other Resources

CategoryCommandLine CategorySecurity CategoryCommandLine

Remove Password Prompt For sudo

These instructions are to remove the prompt for a password when using the sudo command. The sudo command will still need to be used for root access though.

Edit the sudoers file

michael ALL=NOPASSWD: ALL

Type in ^x to exit. This should prompt for an option to save the file, type in Y to save.

Log out, and then log back in. This should now allow you to run the sudo command without being prompted for a password.

Or to do this for the system wide group sudo

Log out, and then back in.

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