Chapter 23. Changing and resetting the root password

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.

restart or change root password in linux
  • A computer running Linux
  • Command-line interface (terminal)

February 25, 2020

Recovering the root password might seem frightening, but it doesn’t have to be difficult or complicated. On a RHEL/CentOS version 7 or later system, thanks to the Grub bootloader it’s actually pretty simple.

And that’s it. You should now have root password access to this system. 

Want to try out Red Hat Enterprise Linux? Download it now for free.

Read Also: How to Reset Forgotten Root Password in Debian 10

To get started, power on or reboot your Linux Mint system. After a few seconds, you should get a grub menu on the screen as shown below.

Linux Mint Grub Menu
Linux Mint Grub Menu

On the first highlighted option, press 'e' on the keyboard to edit the grub parameters. You should get the screen shown below.

Linux Mint Grub Parameters
Linux Mint Grub Parameters

Next, scroll down using the arrow down cursor key until you get to the line beginning with 'linux'. Navigate until you get to the ro quiet splash section and add rw init=/bin/bash.

Change Linux Mint Grub Parameter
Change Linux Mint Grub Parameter
Linux Mint Single-User Mode

To reset the forgotten root password in Linux Mint, simply run the passwd root command as shown.

# passwd root

Specify the new root password and confirm it. If the password matches, you should get a ‘password updated successfully‘ notification.

Reset Root Password in Linux Mint
Reset Root Password in Linux Mint

If you read this far, tweet to the author to show them you care. Tweet a thanks

Photo of author

Все знают, что с паролями нужно обращаться аккуратно, записывать их в надежном месте, чтобы не забыть. Но знание это одно, а на деле получается совсем по-другому. У многих пользователей часто пароли теряются, особенно, если вы ими не пользуетесь. А как вы знаете, архитектура Linux не позволит выполнить какие-либо административные действия без прав суперпользователя.

Поэтому даже если при серфинге в интернете пароль пользователя вам не нужен, при условии, что вы настроили автоматический вход в систему, то уже установить программу без него или изменить настройки системы вы не сможете. В этой статье мы рассмотрим как выполняется сброс пароля Ubuntu если вы его забыли.

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

Дополнительно:  Может ли ноутбук работать без аккумуляторной батареи

Но Ubuntu пошла другим путем. Здесь тоже есть суперпользователь, но из соображений безопасности, по умолчанию, вы не можете авторизоваться от его имени. Все действия выполняются через утилиту sudo от имени обычного пользователя. Пароль для пользователя root не задан и трогать его мы не будем. А будем восстанавливать пароль для текущего пользователя.

Если вы не знаете какое имя у вашего текущего пользователя, его можно посмотреть с помощью такой команды:

Это имя пригодится вам для сброса пароля.

In this article, you will learn how to reset the forgotten root password on Ubuntu 18.04 LTS and Ubuntu 20.04 LTS.

Firstly, you need to either power on or reboot your Ubuntu system. You should get a grub menu as shown below. If you are running your system on VirtualBox, press the ‘SHIFT’ key on the keyboard to bring up the boot menu.

Ubuntu Grub Menu
Ubuntu Grub Menu

Next, press the 'e' key to edit the grub parameters. This should display a screen as shown below.

Grub Boot Parameters
Grub Boot Parameters

Scroll down until you get to the line that begins with 'linux /boot/vmlinuz' the entire line is highlighted below.

Find Grub Boot Parameter
Find Grub Boot Parameter

Narrow down to a section that reads "ro quiet splash $vt_handoff".

Locate Grub Boot Parameter
Locate Grub Boot Parameter

Replace "ro quiet splash $vt_handoff" with rw init=/bin/bash as shown. The aim is to set the root file system with read and write commands denoted by the rw prefix.

Enable Root Filesystem
Enable Root Filesystem

Thereafter, press ctrl + x or F10 to reboot your system. Your system will boot into a root shell screen as shown below. You can confirm that the root filesystem had read and write access rights by running the command.

# mount | grep -w /

The output in the screenshot below confirms read and write access rights denoted by rw.

Confirm Root Filesytem Permissions
Confirm Root Filesytem Permissions

To reset the root password execute the command.

# passwd 

Provide a new password and confirm it. Thereafter, you will get a ‘password updated successfully’ notification.

Reset Root Password in Ubuntu
Reset Root Password in Ubuntu

With the root password successfully changed, reboot into your Ubuntu system by running the command.

# exec /sbin/init

Thank you for coming this far. We hope that you can now comfortably reset the forgotten root password on your Ubuntu system from the grub menu.

Дополнительно:  How to Change MySQL Root Password in Ubuntu 22.04

If you read this far, tweet to the author to show them you care. Tweet a thanks

Photo of author


It is not common to log in as root, so we do not use its password for a long time. We may forget and the sudo command is not available. If this happens, let’s look at two ways to recover your forgotten root password on Debian and Ubuntu.

To reset the forgotten root password, you must first log in to GRUB menu. To do this, you need to start / restart the computer. In this example today, I have two On a VirtualBox machine I will present the steps of this operation in parallel.

System restart / reboot

Boot the machine and wait for GRUB to start. For Ubuntu systems, if the GRUB menu does not appear automatically, press and hold the left button at the beginning of the boot process. key. So for me, the GRUB menus for Debian 10 (Buster) and Ubuntu 20.04 LTS (Focal Fossa) look like this:

Дополнительно:  Samsung SM-A205U Root With Magisk

Booting Virtual Machines - Debian 10 (Buster) and Ubuntu 20.04 LTS (Focal Fossa) - Booting GRUB Menus

In the beginning, until the windows fit side by side on the table, I will show the first few steps together.

Start the root console

On Debian, select «Advanced settings for Debian GNU / Linux» and on Ubuntu, select «Advanced options for Ubuntu». This is where the special options for both systems come in:

GRUB menu - Advanced settings on Debian and Ubuntu

If you have more than one operating system, of course, select the appropriate system on which you want to reset the root password.

Then press the key, the GRUB parameters will appear:

Open GRUB parameters

Here, scroll down to the bottom of the text box where you will find the Linux kernel loader:

GRUB parameters - Find the Linux kernel load section

Here you have to change that ro (read only) rw (read / write), that is, to mount the root filesystem in writable mode, and to start the Bash-him.

rw maybe-ubiquity init=/bin/bash

Finally, it should look something like this:

GRUB parameters - Modify the Linux kernel load section

Of course, for other versions of GRUB / Debian / Ubuntu, there may be other options, but the point is to fix ro to rw and add the «init = / bin / bash» section to the end of the line.

To start the configuration, press key, you will get a root console:

Debian root console

In the case of Ubuntu, it loads a little more, and finally we get a root prompt here:

Ubuntu root console

Change root password

passwd root

Then enter any new password and repeat.

Changing the root password on Debian

Change root password on Ubuntu

exec /sbin/init

Login with root

Debian root login

Ubuntu root login

Why do you need to change the password in Ubuntu? Let me give you a couple of scenarios.

  • Change user password via the command line
  • Change root user password
  • Change user password via GUI

Change user password in Ubuntu [Command Line]

If you want to change your current password, simply run this command in a terminal:


You’ll be asked to enter your current password and the new password twice.

You won’t see anything on the screen while typing the password. This is perfectly normal behavior for UNIX and Linux.

Change password of the current user using "passwd" command
Change Password using passwd

Sometimes, the passwd command will throw errors like:
Small Password: If the new password is shorter than 8 characters
Fails Dictionary Check: Does not contain enough different characters. So, use some other characters than just numbers and try again.

sudo passwd <user_name>
Change the password of another user in Ubuntu terminal
Change another user password

If you changed your password and forgot it later, don’t worry. You can easily reset Ubuntu password.

How to Reset Forgotten Ubuntu Password in 2 Minutes

Change (or set) the root password in Ubuntu

You can set or change root password using the passwd command. However, in most cases, you don’t need it and you shouldn’t be doing it.

Now, about changing the root password.

Else, you can change it using the existing root password.

sudo passwd root
Change root password using "passwd" command
Change Root Password

Change Ubuntu password using GUI

I have used GNOME desktop with Ubuntu 22.04 here. The steps should be more or less the same for other desktop environments and Ubuntu versions.

Go to Overview (press Windows/Super key) and search for Settings.

Go to Users in Ubuntu GNOME settings and Unlock the section using the current logged in user password
Select Users and Unlock it
Changing user password in Ubuntu
Change Password of the User

Now, select Set password Now option on the dialog box and type and confirm the new password. If you are changing your own password, you’ll also have to enter your current password.

Changing the current user password in Ubuntu needs to type the existing password also
Enter Current user password also

How to Reset Forgotten Ubuntu Password in 2 Minutes

More on user passwords in Linux

Passwd command in Linux: 8 Practical Examples

Here’s a fun thing you can do with sudo so that it makes fun of you when you enter incorrect password.

And get familiar with the Seahorse password manager app in Linux desktops.

Seahorse: Manage Your Passwords & Encryption Keys in Linux

Red Hat Training

A Red Hat training course is available for RHEL 8

23.1. Changing the root password as the root user

  • Root access
  • To change the root password, use:

    # passwd

    You are prompted to enter your current password before you can change it.

23.2. Changing or resetting the forgotten root password as a non-root user

  • You are able to log in as a non-root user.
  • You are a member of the administrative wheel group.
  • $ sudo passwd root

    You are prompted to enter your current non-root password before you can change the root password.

23.3. Resetting the root password on boot

  1. Reboot the system and, on the GRUB 2 boot screen, press the key to interrupt the boot process.

    The kernel boot parameters appear.

    set gfx_payload=keep
    insmod gzio
    linux ($root)/vmlinuz-4.18.0-80.e18.x86_64 root=/dev/mapper/rhel-root ro crash\
    kernel=auto resume=/dev/mapper/rhel-swap rhgb quiet
    initrd ($root)/initramfs-4.18.0-80.e18.x86_64.img $tuned_initrd
  2. Go to the end of the line that starts with .

     ($root)/vmlinuz-4.18.0-80.e18.x86_64 root=/dev/mapper/rhel-root ro crash\
    kernel=auto resume=/dev/mapper/rhel-swap rhgb quiet

    Press to jump to the end of the line.

  3. Add rd.break to the end of the line that starts with linux.

     ($root)/vmlinuz-4.18.0-80.e18.x86_64 root=/dev/mapper/rhel-root ro crash\
    kernel=auto resume=/dev/mapper/rhel-swap rhgb quiet 
  4. Press to start the system with the changed parameters.

    The switch_root prompt appears.

  5. Remount the file system as writable:

    mount -o remount,rw /sysroot

    The file system is mounted as read-only in the /sysroot directory. Remounting the file system as writable allows you to change the password.

  6. Enter the chroot environment:

    chroot /sysroot

    The sh-4.4# prompt appears.

  7. Reset the root password:

  8. Enable the SELinux relabeling process on the next system boot:

    touch /.autorelabel
  9. Exit the chroot environment:

  10. Exit the switch_root prompt:

  11. Wait until the SELinux relabeling process is finished. Note that relabeling a large disk might take a long time. The system reboots automatically when the process is complete.
  1. To verify that the root password is successfully changed, log in as a normal user and open the Terminal.
  2. Run the interactive shell as root:

    $ su
  3. Enter your new root password.
  4. whoami

    The output returns:


Как сбросить пароль с помощью Grub

Если у вас нет пользователя, с помощью которого вы могли бы изменить пароль в системе, то это можно сделать с помощью другого Linux дистрибутива или Recovery Mode. В загрузчике Grub вы можете менять параметры, передаваемые ядру. Например, вы можете передать параметр init, который попросит ядро выполнить вместо системы инициализации вашу команду. Но для этого вам надо меню загрузчика Grub. Если меню Grub вообще не показывается, а вместо этого сразу начинается загрузка операционной системы, зажмите правый Shift до начала загрузки системы, меню должно появится:

Для того чтобы настроить параметры ядра, выберите пункт меню, с которым вы обычно загружаетесь, например, первый и нажмите клавишу E. Откроется редактор конфигурации выбранной секции. Вы можете использовать стрелки вверх-вниз, вправо-влево для перемещения по тексту. Тут вам необходимо найти строчку, начинающуюся со слова linux. В конце неё есть два параметра: quiet splash.

Первый параметр указывает, что надо выводить минимум информации во время загрузки, а второй — показывает заставку. Если заставку не отключить, то в последних версиях Ubuntu вы можете не увидеть консоль восстановления. Поэтому удалите их, а вместо них добавьте: verbose init=/bin/bash. Должно получится вот так:

Для загрузки с этой конфигурацией нажмите Ctrl+X. Обратите внимание, что измененная конфигурация действует только для текущей загрузки и никуда не сохраняется. Если всё прошло хорошо, то вы увидите такую консоль:

По умолчанию, в режиме восстановления корневая файловая система монтируется только для чтения чтобы вы случайно ничего не повредили, но так мы не сможем изменить пароль, поэтому нужно перемонтировать ее для чтения/записи:

mount -o remount,rw /

Осталось только ввести новый пароль. В результате команда должна вывести сообщение: password updated successfully. Это будет означать, что команда выполнена успешно. Если вы хотите сбросить пароль root Ubuntu, то имя пользователя достаточно изменить на root:

Но я бы не советовал выполнять сброс пароля root ubuntu, если вы не уверенны что вам это нужно. Лучше придерживаться решения разработчиков дистрибутива.

Changing the Root Password in CentOS

Changing a password in CentOS is almost identical to changing it in Ubuntu.

Step 1: Access the Command Line (Terminal)

Right-click the desktop, then left-click Open in Terminal.  Or, click Menu > Applications > Utilities > Terminal.

Step 2: Change the Password

sudo passwd root
change root password in centos

This is a similar process as in Ubuntu, with a couple of variations.

Step 1: Access Boot Menu

Restart the system, then tap the Esc key about once per second to launch the GRUB menu.

Step 2: Edit Boot Options

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.

Step 3: Remount the Drive

mount / -o remount,rw

Step 4: Changing the Password


Press Enter, and the system should prompt you to enter and confirm a new password.

Step 5: 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.

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.

Step 1: 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.

Step 2: 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.

Step 3: 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.

Step 4: Change the Password

At the prompt, type:

passwd username
shutdown –r

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 Your Root Password in Ubuntu

Step 1: Open a Terminal Window

Right-click the desktop, then left-click Open in terminal.

Alternately, you can click Menu > Applications > Accessories > Terminal.

Step 2: 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.

change root password in ubuntu terminal command

Сброс пароля Ubuntu с помощью sudo

А затем ввести пароль текущего пользователя:

И два раза ввести новый пароль для пользователя, пароль которого вы забыли.

Но не всегда все так просто и о запасном варианте мы вспоминаем только тогда, когда создавать его уже поздно. Поэтому есть еще один способ, которым можно выполнить восстановление пароля Ubuntu.


  • Introductory
  • Recover a forgotten root password using the GRUB menu
  • Recover a forgotten root password using GParted Live
  • Conclusion

Recover a forgotten root password using GParted Live

If there is no GRUB loader installed on the machine, or the machine is booting with another boot manager program that we do not know, then as an alternative we have other options to reset our forgotten root password.

For this purpose, the Live installation kit of virtually any Linux distribution (which of course has one) is great, such as Debian or Ubuntu Live installers, the point is to boot a Linux system and have a root terminal or console.

In this example, I will perform this task with GParted Live. It is a Debian-based, featherweight small system designed specifically to perform such recovery, repair, and maintenance tasks. I have previously made another description of this, the steps of which I will not detail here, so you can find the link below on how to get it, how to write it to a flash drive, and how to start a root terminal in it (link opens in a new window meg):

Booting the root terminal

From now on, I will not split the examples for Debian and Ubuntu, because here the Live system will work on any distribution, we will have to reset the root password. So I’m now opening a root terminal in GParted Live, and the steps so far can be found in the description above:

GParted Live - Root terminal and GParted program

GParted Live starts the GParted partitioning program by default, which I leave outside so I have the drives, partitions, and markers in front of me. We will need these.

Mount a system partition

fdisk -l

GParted Live - Find a system partition

If you are not familiar with partitions, you can easily decide which partition you need based on the size, type, and boot-flag status of the partition.

In this example, the virtual machine has multiple partitions, of which here is / Dev / sda1 The parameters just mentioned are 36 GB, type: Linux, ext4 file system, and boot flag. So in this example, this will be fine.

Create a mount point for this partition and mount it:

mkdir  /mnt/system
mount  /dev/sda1  /mnt/system

GParted Live - Mount a system partition

Chrooting the system partition

In the next step, we need to pretend that this mount point (/ mnt / system) is our regular filesystem, this is called chrooting:

chroot  /mnt/system

After issuing the command, it throws a warning that it can’t set the correct localization, but we don’t have to deal with that. We will then be taken to the root directory, which is already the root directory of the mounted drive:

GParted Live - Chrooting the system partition

Interestingly, the output of our prompt and our ls command also became colored here. This is because the original Debian 10 (Buster) minimal server installation anno I set the color prompt, and now the .bashrc file for this system has run from the / root directory. So from this we can see that the chroot succeeded. Thus, the output of the ls command also returned the contents of the mounted system partition.

Change root password

You can then easily change the root password:

passwd root

GParted Live - Change root password

Enter the new root password twice in succession.

Exit and reboot system

In the end, there was nothing left but to step back from everything:

Exit the chroot shell:


Unmount the system partition:

umount /mnt/system

This is very important because if you do not unmount and restart the machine, the file system may be damaged!

And you can also exit root:


GParted Live - Log out

Then remove the Live Installer from the DVD or USB and restart the computer.

Login with root

Login with root


В этой небольшой статье мы рассмотрели как сменить пароль в Ubuntu в операционной системе или с помощью режима восстановления. Как видите, это не так сложно. Если вы хотите чтобы никто не смог получить доступ к вашему паролю нужно использовать шифрование всего диска, например, LUKS. Более подробно узнать о работе утилиты passwd вы можете в статье как сменить пароль Linux. Пусть у вас никогда не возникает ситуации забыл пароль ubuntu, пароли надо надежно сохранять, запоминать, или, на крайний случай, записывать на бумаге!

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


With these two methods, we can rest assured that we can reset the root password if we accidentally forget it. However, this also means that if unauthorized people have access to our computer or laptop, they can change our root password and access our data in the same way. We can protect against this with disk encryption, which can make things harder for unauthorized intruders.

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