It’s a good idea to change your passwords regularly and consider using enterprise password management software.
This guide will help you change your Linux root password in Ubuntu or CentOS, or reset the password.

STEP 1: Start your OS and you will see this screen as soon you start your OS.

Press e, a new screen will come as shown below.

The place where green arrow is there, type
.Press Ctrl+X to continue that process.When BIOS loads up your OS, in between that rd.break will stop that process there and enforcing will stop the security of RHEL which is SELINUX from any intervention.

STEP 2: you will get this screen like shown below

You are in Emergency mode now. This is the main screen and most of the work will be done here.command 1:
mount -o remount, rw /sysroot/
STEP 3:So, a last command to decrypt that filecommand 3:
CentOS — дистрибутив Linux, основанный на коммерческом Red Hat Enterprise Linux компании Red Hat и совместимый с ним. Рутовая учетная запись – специальная учетная запись пользователя в Linux, которая имеет доступ ко всем файлам, всем командам и которая может делать практически все-все-все на сервере Linux. В этой инструкции расскажем как поменять пароль на операционной системе Centos 8. Эта инструкция подойдет вам на тот случай, если вы знаете текущий пароль учетной записи пользователя.

Для изменения пароля root в CentOS 8 необходимо иметь права sudo или иметь действительный пароль учетной записи root.
В командной строке sudo –l
Отображается такое диалоговое окно? Значит вы сможете сменить текущий пароль. Если вы устанавливали CentOS 8 с настройками по умолчанию, то возможно, вы решили заблокировать учетную запись root по умолчанию. Изменение пароля root разблокирует учетку.
$ sudo passwd
Retype new password:
passwd: all authentication tokens updated successfully.
Для подключения от имени пользователя root в CentOS 8 используем команду «su» без аргументов:
$ su —
Другой метод смены пароля — при помощи команды su.
Подключаемся как root:
Теперь запускаем команду «passwd» без каких-либо аргументов:
На этом инструкция считается завершенной.
- Resetting Forgotten Root Password
- Resetting Root password from Terminal
- Conclusion
- Changing the User Password through GUI
- Changing the User Password through Terminal
- How to change another user’s Password in CentOS
- Changing Your Root Password in Ubuntu
- Change Your Root Password
- Resetting a Root Password in Ubuntu
- Boot to Recovery Mode
- Drop Out to Root Shell
- Remount the File System with Write-Permissions
- Change the Password
- Changing the Root Password in CentOS
- Remount the Drive
- Changing the Password
- Restart
Resetting Forgotten Root Password
If you have forgotten your password and after trying a lot to remember your old password, you are still unable to get that. Do not worry; we can reset the root password from the GRUB Boot Menu.
For resetting the root password, first, reboot your computer.

When the system restarts, press the “ESC” key immediately to interrupt the boot process.
Select the kernel from the GRUB/Boot menu you want to boot into by pressing the arrow keys.

Pressing ‘e’ from your keyboard will open the editing menu.

In the editing menu, locate the “ro” kernel parameter and replace it with “rw,” and add an additional parameter “init=/sysroot/bin/sh”:


Now run the “chroot /sysroot” command to convert the root file system in read and write mode:

You will now be able to change the root password.
To set a new password for root, input the command:

You will then be asked to input a new password and then confirm it. It is best to use a unique, complex, and complicated password that is easy to remember.



Once everything is changed and saved, reboot your computer by using the “reboot” command:

You may need to wait a few minutes to let the SELinux relabelling process complete.

Upon completion, the system will reboot, and the login screen will appear.

Resetting Root password from Terminal
If you need to reset your root password and know the current password, there is no need to do anything complex. Just fire up your CentOS 8 terminal and type the command given below:

Please do not select common words as your password.
Conclusion
In this article, we’ve learned how to reset a root password that is forgotten. Moreover, we also learned to set up a new root password if you remember your current password.
A Javascript Developer & Linux enthusiast with 4 years of industrial experience and proven know-how to combine creative and usability viewpoints resulting in world-class web applications. I have experience working with Vue, React & Node.js & currently working on article writing and video creation.
Data is precious. Some people are even calling it the new Gold. It is essential to change your password from time to time to ensure that your data remains protected from malicious activities. Most people only have a single password for everything, and they use it for years which is an unsafe practice and can expose them to dangerous cybercrimes like identity theft. When setting a password, one should always ensure to set a unique and strong password.This article will present an extensive guide on changing your password on CentOS 8 operating system by using two different methods.
Changing the User Password through GUI
Step 1: First, open the dropdown menu from the top right corner:





Step 6: It will open a new window, where you can enter your current password to confirm and the new password that you want to set:

After entering your passwords, click on the change button on the window’s top right corner, as highlighted in the above screenshot.
Congratulations! Your password has been changed successfully using the GUI of CentOS. From here on out, you will have to use the new password to login into your account.
Changing the User Password through Terminal
When you are using a CentOS 8 server only without a GUI, and you only have access to the terminal of the CentOS 8 Operating system, then the GUI method won’t work. We have to change the password using the terminal, and we can do so easily.
Step 1: First of all, open up the terminal of the CentOS 8 Operating system from the application menu.
Step 2: In the terminal, type the “passwd” command and press Enter to change the password:
You will be asked to input your current password:

If you have entered the correct, current password, it will ask you to input your new password:

Once you entered the new password that you want to set, it will ask you to confirm your new password:

The password will get changed if both passwords match, and a success message will appear on the terminal.

How to change another user’s Password in CentOS



The terminal will directly ask you to input the new password and confirm the new password:

You will get a success message:

As mentioned above, Data protection is a modern-day necessity. Data is now being labeled as a valuable commodity. Nowadays, it has become an absolute must to use unique, complicated, and strong passwords to protect your data.

Существуют
различные способы сброса пароля root:
— Загрузка в однопользовательском режиме.— Используя загрузочный диск отредактировать файл passwd .— Смонтировать диск в другую систему и изменить файл passwd .
1) Сброс
пароля с помощью загрузки в однопользовательском режиме.
Сброс
пароля root в CentOS 7 и RHEL 7
В
однопользовательском режиме система запускает однопользовательскую оболочку, в
которой вы можете запускать команды без каких-либо учетных данных (имя
пользователя и пароль), вы попадаете прямо в ограниченную оболочку с доступом
ко всей файловой системе.
В
CentOS 7 и RHEL 7 порядок получения доступа к системе во время процесса
загрузки и изменения пароля root изменился из-за принятия Systemd.

В
начале процесса загрузки в меню GRUB нажмите на клавиатуре клавишу
«e» для редактирования.
Затем
перейдите к строке ядра (строка, начинающаяся с linux) и измените строку с
параметром ro. Замените ro на rw init=/sysroot/bin/sh

а
также добавьте следующие операторы в конце:
rd.break enforcing=0
Примечание:
rd.break запрашивает перерыв на ранней стадии процесса загрузки.
enforcing
= 0 переводит систему в разрешающий режим SELinux. Не путайте с selinux = 0,
который полностью отключает SELinux.
Нажмите
Ctrl + X, чтобы возобновить процесс загрузки.
Выполните
команду chroot в разделе / sysroot:
Войдите
в систему как пользователь root и введите следующую команду, чтобы изменить
пароль пользователя root файле /etc/passwd.
# passwd root

Сброс
пароля root в CentOS 6 и RHEL 6
При загрузке
нажмите кнопку «e»для
редактирования параметров загрузки

С помощью клавиш вверх/вниз на
клавиатуре выберите второй пункт «kernel /vmlinuz» и нажмите на клавиатуре «e».

Появится возможность отредактировать
параметры загрузки. Для загрузки CentOS 6 в режиме single mode допишите через пробел в конец строки с параметрами
‘s’ или ‘single’ как показано на следующем скриншоте. После нажмите Enter, а потом выберите загрузку операционной системы в этом
режиме, выбрав его с помощью вверх/вниз и нажав
«b» на клавиатуре.

С помощью «passwd» установите новый пароль. В случае успешного выполнения операции появится сообщение:
Passwd:
all authentication tokens updated successfully.

Если злоумышленник может иметь физический доступ к серверу, он также сможет выбрать ядро для загрузки из пункта меню grub, просто нажав клавишу «e» на клавиатуре, чтобы изменить параметр загрузки ro и загрузиться в однопользовательском режиме на CentOS без запроса пароля пользователя root, даже если строка SINGLE=/sbin/sushell заменена на SINGLE=/sbin/sulogin в файле /etc/sysconfig/init. Единственный способ защитить паролем однопользовательский режим в CentOS — это защитить GRUB паролем, используя следующие инструкции.
Как защитить
паролем Grub в CentOS
Сначала
создайте надежный зашифрованный пароль с помощью утилиты grub2-setpassword
Теперь
откройте файл /boot/grub2/grub.cfg и найдите загрузочную запись, которую вы
хотите защитить паролем, она начинается с menuentry . Когда запись —unrestricted
, удалите из —unrestricted параметр —unrestricted .
Сохраните
файл и закройте, теперь попробуйте перезагрузить CentOS и измените загрузочные записи, нажав клавишу e
, вам будет предложено предоставить учетные данные, как показано на скриншоте.
GRUB-меню CentOS успешно защищено
паролем.
2)
Сброс пароля root помощью редактирования файла /etc/passwd
Если у вас установлена 32 битная ОС, вам потребуется загрузочный диск с Linux x32 и наоборот. Загрузитесь с Live-диска или установите
жесткий диск, где установлена система с забытым паролем в другой компьютер с ОС
Linux.
# mkdir /mnt/centos
Определите
системный диск (sda1, sda2). Утилита fdisk выведет информацию о существующих разделах диска.
Смонтируйте системный раздел:
# mount /dev/sda2 /mnt/centos
Необходимо изменить файл /mnt/centos/etc/shadow, удалив из него хэш пароля пользователя root
# sudo vi /mnt/centos/etc/shadow

Т.е. между „root” и номером группы пользователя “root” должно
стоять два знака двоеточия «::» (root::0). Нажмите Esc чтобы выйти из режима редактирования, сохраните файл — нажмите «:wq» и Enter.
В /mnt/centos/etc/passwd в строке, относящейся к root символ «x» необходимо заменить на, «*». Помните,
что файлы /etc/passwd и /etc/shadow, относятся к Live-системе.
Перезагрузите
систему. Введите имя пользователя root, на запрос пароля нажмите Enter и после этого сможете попасть в
систему без пароля. После перезагрузки не забудьте сразу новый пароль у
пользователя root.
Changing Your Root Password in Ubuntu
Right-click the desktop, then left-click Open in terminal.
Change Your Root Password
sudo passwd root
The system will prompt you to enter your password – this is the same password you use to log in to the system.
Next, the system will prompt you to enter a new password. Do so, and then re-enter it exactly the same when the system prompts you to retype the password. This double-entry confirms that you have typed the password correctly.

Resetting a Root Password in Ubuntu
In some situations, you may need to access an account for which you’ve lost or forgotten a password.
Boot to Recovery Mode
Restart your system. Once you see the splash screen for the computer manufacturer, hold down the shift key. The system should come up with a black and white GRUB, or boot menu, with different Linux kernel versions displayed.
Drop Out to Root Shell
The system should display a menu with different boot options. Use the arrow keys to navigate to the option labeled root and press Enter.
The system should respond by giving you a command-line interface with a prompt.
Remount the File System with Write-Permissions
Right now, your system only has read-only access to your system. That means it can look at the data, but cannot make any changes. But we need write-access to change the password, so we’ll need to remount the drive with the appropriate permissions.
At the prompt, type:
mount –o rw,remount /
Press Enter. This should allow you to make changes to the data on the hard drive.
Change the Password
Hit Enter, and your system should restart. Don’t press any keys, let the system come up to the login screen, and test to make sure the new password works.
Note: Learn how to use the chpasswd command. Chpasswd is helpful for managing multiple passwords and making multiple changes.
Changing the Root Password in CentOS
Changing a password in CentOS is almost identical to changing it in Ubuntu.

This is a similar process as in Ubuntu, with a couple of variations.
Restart the system, then tap the Esc key about once per second to launch the GRUB menu.
Use the arrows to highlight the version of Linux you boot into, then press e.
Use the arrows to highlight the line that starts with kernel or Linux.
Remount the Drive
mount / -o remount,rw
Changing the Password
Press Enter, and the system should prompt you to enter and confirm a new password.
Restart
mount / -o remount,ro
Your system should restart. Confirm that your new password works by logging in.
Note: If you ever come across a Linux boot failure, be sure to save our guide on using GRUB rescue to troubleshoot it.
It can be more challenging if you’ve lost or forgotten a password, but with a little creative restarting and editing, you shouldn’t find it too hard.






