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:
Два нижеописанных варианта подходят для сброса root на VDS с KVM-виртуализацией и Linux-подобной ОС CentOS версии 6.
Нужно создать удалённое подключение к виртуальному серверу по сетевому протоколу SSH. Проще всего это сделать через бесплатную программу-клиент PuTTY (для Windows) или встроенный SSH-клиент для Mac OS.
Есть много удобных серверных клиентов и для пользователей мобильных устройств. Например, JuiceSSH для Android или Termius для iOS.
- Смена пароля root с помощью PuTTY
- Reset Forgotten Root Password in RHEL/CentOS & Fedora
- Reset Forgotten root Password in CentOS 8
- 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 the Root Password in CentOS
- Change the Password
- Remount the Drive
- Changing the Password
- Restart
- Как изменить пароль root на VDS, когда он неизвестен
- Change Your Root Password
- Об этой статье
- Boot to Recovery Mode
- Drop Out to Root Shell
- Remount the File System with Write-Permissions
Смена пароля root с помощью PuTTY
This article will guide you through simple steps to reset forgotten root password in RHEL-based Linux distributions such as CentOS 8 and Fedora 35/34.
Reset Forgotten Root Password in RHEL/CentOS & Fedora
First, restart your system, and at the boot grub menu choose the kernel (mostly the first option) you wish to boot into and press the key ‘e’ on your keyboard.
RHEL 8 Boot Menu
Append Kernel Parameter
On the next screen, you will land into emergency mode, here press Enter key to get into the shell prompt. Now, make sure to confirm that you remount the sysroot directory with read and write permissions. By default, it is mounted with read-only mode indicated as ro.
Confirm Sysroot Directory Permissions
Now remount the sysroot directory with read and write permissions and confirm the permissions again. Note that this time, the permissions have changed from ro (read-only) to rw (read and write) as shown.
Mount Sysroot Directory
# chroot /sysroot
Next, use the passwd command to reset the root password with the new password and confirm it.
Reset Root Password
# touch /.autorelabel
Enable SELinux Relable
Finally, type exit and then log out to start the SELinux relabelling process.
RHEL 8 Login
And that’s how you would reset a forgotten root password in RHEL/CentOS 8 and Fedora 35/34 Linux distributions.
Read Also: How to Set Up Automatic Updates for CentOS 8 and How to Reset Forgotten Root Password in RHEL 8
Reset Forgotten root Password in CentOS 8
First, reboot or power on your CentOS 8 system. Select the kernel you want to boot into. Next, press ‘e’ on the keyboard to interrupt the boot process and make changes.
CentOS 8 Boot Menu
On the next screen, locate the ro (read-only) kernel parameter as highlighted below.
Locate Kernel Parameter
Replace the kernel parameter ro with rw and append an extra kernel parameter init=/sysroot/bin/sh. In a nutshell, simply replace the kernel parameter ro with rw init=/sysroot/bin/sh.
Replace Kernel Parameter
Next, run the command below to mount the root file system in read and write mode.
:/# chroot /sysroot
Mount Root File System
You can now change the root password by executing the command:
:/# passwd root
Provide a new root password and confirm it. For best practice select a password with a combination of uppercase, lowercase, numerical and special characters to boost password strength.
Next, run the command below to enable SELinux relabelling.
:/# touch /.autorelabel
To apply the changes, exit and reboot the CentOS 8 system.
:/# exit
:/# reboot
Reboot CentOS 8 System
Upon reboot, the SELinux relabelling process will commence. Give it about 3 minutes.
We hope this tutorial will be beneficial to you. Feel free to weigh in your feedback if you are stuck.
Well here is the guide which will take you out of any such situation if you ever get into it. Here in this article we will be taking you to the journey of resetting your RHEL 7 and CentOS 7 root password.
This very morning I turned my RHEL 7 Linux server to find out that it has been locked. Either I messed up with password I changed last night or I have really forgotten it.
Press ‘e’ to Edit Boot Menu
After you press ‘e’ from keyboard you would see a lot of text which may be clipped as per the size of your screen.
Search for the text “rhgb quiet” and replace it with “init=/bin/bash” without quotes.
Once done editing press ‘ctrl+x’ and it will start booting with specified parameter. And you will get bash prompt.
Check Root Mount Status
You may notice that root partition is reported to be ‘ro’ (Read Only). We need to have read-write permission on root partition to change the root password.
# mount -o remount,rw /
Also cross check, if the root partition is mounted with read-write permission mode.
Set Permissions on Root Partition
Now you can change the root password by typing the passwd command. But that is not done. We need to relabel SELinux context. If we skip relabeling the whole SELinux context we would be able to login using using password.
Reboot and login again to root account and see if everything works ok or not?
# exec /sbin/init
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.
Два нижеописанных варианта подходят для сброса root на VDS с KVM-виртуализацией и Linux-подобными ОС. Например — ОС Debian, CentOS, Ubuntu.
В этом обзоре мы рассмотрим процесс сброса пароля для операционной системы centOS 7.
Поменять пароль root в этом случае можно через панель VMmanager, используя встроенную систему удалённого доступа к серверу Virtual Network Computing (VNC).
Теперь можно загрузится в штатном режиме с уже действующим новым паролем.
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.
Из этой статьи вы узнаете, как в Linux изменить пароль суперпользователя, если вы знаете текущий пароль, и если вы его не знаете .
Существуют
различные способы сброса пароля 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.
Сброс
пароля 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 the Root Password in CentOS
Changing a password in CentOS is almost identical to changing it in Ubuntu.
Change the Password
sudo passwd root
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.
Как изменить пароль root на VDS, когда он неизвестен
Right-click the desktop, then left-click Open in terminal.
Change Your Root Password
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.
Об этой статье
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.
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.