We have run the commands and procedures mentioned in this article on an Ubuntu 22.04 LTS system.
Need help in creating a strong password? Then take a look here: 7 Methods to Generate a Strong Password in Ubuntu
A few things to note:
- You should have access to the system as a root or non-root user
- You need to be root or have sudo access to change passwords for other users
This article is not about resetting your server’s root password if you cannot access it. That’s an entirely different topic.
su other_username
A few things you should know here:
- If you were logged in as a normal user, you’d be asked to enter the password of the other user
- The root user can switch to other users without needing the passwords of those accounts
- If you have sudo access, you can use
sudo su other_username
to switch user without the password of the other user
su -l other_username
compgen -u
- Introduction
- Temporary Switching to root
- Changing Root Password
- Conclusion
- How to Change the Root Password of Ubuntu using the Command Line
- How to Change the Root Password of Ubuntu using the passwd Command
- Step 1: Open Setting
- Step 2: Change Password
- Change lost or forgotten passwords in Ubuntu 17.10
- Change user password in Ubuntu [Command Line]
- Change (or set) the root password in Ubuntu
- Change Ubuntu password using GUI
- More on user passwords in Linux
- What is root user? Why is it locked in Ubuntu?
- How to run commands as root user in Ubuntu?
- How to become root user in Ubuntu?
- How to enable root user in Ubuntu?
- Как изменить пароль другого пользователя в Ubuntu и производных?
- Как восстановить пароль root?
- Reset Ubuntu password from recovery mode
- Step 1: Boot into recovery mode
- Step 2: Drop to root shell prompt
- Step 3: Remount the root with write access
- Step 4: Reset username or password
- Possible Troubleshoot:
- Alternate method to reset Ubuntu password
- Step 1
- Step 2
- Step 3
- Step 4
- If resetting Ubuntu passwords is this easy, isn’t this a security risk?
- Bonus Tip: Handling the possible keyring issue after changing the password
- Did it help you?
- 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
- Change the password for your own account
- Сбрасываем пароль от root через GRUB
- Log in as root user
- Run a command as another user
- Switch to root user
- What is a Root user?
- About the Article
- An Alternative
- Open the Ubuntu command line
- Switching users into their login shell
- Resetting the root password
- Step 1: Booting to Recovery
- Step 2: Changing the configurations
- Step 3: Rebooting the system
- Step 4: Changing the root password
- Change password for other user accounts
- Unlock/lock root account
- Get Temporary root access through the sudo command
- Change the sudo password through the passwd command
- Changing the root password
- Switch to another user from a regular user
- How to change the root password (An alternative approach)?
- Switching to a normal user from root user
- Exit the root login and then the Terminal
Introduction
Temporary Switching to root
sudo command-name
sudo su -
whoami
Output
root
Changing Root Password
sudo passwd root
The new root password will be required to be entered and confirmed.
Make sure you use a strong and unique password when creating the password. The most critical part of your account’s security is having a strong password. A strong password often consists of at least 16 characters, one uppercase letter, one lowercase letter, one number, and one special character.
When you type the password, it does not appear on the screen.
Output
Enter new UNIX password:
Retype new UNIX password:
passwd: password updated successfully
That’s it. The password for the root account has been updated.
You can now use the new password to log in to your Ubuntu system as root.
Conclusion
The root account in Ubuntu has no password by default. To run commands with root capabilities, the sudo command is advised.
You’ll need to set the root password before you can log in as root.
If you have any queries, please leave a comment below and we’ll be happy to respond to them.
Ubuntu is the one of the best Linux distros that can be installed on servers as well as desktop computers (PC). Ubuntu, which is based on Debian’s design have the access to several functions, one of which is changing the root password. Changing your passwords frequently reduces the likelihood of being hacked that will also make your system more secure.
- Change the Root Password of Ubuntu using Command Line
- Change the Root Password of Ubuntu using passwd command
- Change the Root Password of Ubuntu using Graphical User Interface
How to Change the Root Password of Ubuntu using the Command Line
You’ll be asked to create and confirm a new password. The output will show that the password has been successfully updated.
How to Change the Root Password of Ubuntu using the passwd Command
Now run the mentioned below command to alter the password.
Now enter your new password and confirm that password again.
Step 1: Open Setting
Open Activities overview, in the search bar type “setting” click on the setting icon and a new window will get open.
Step 2: Change Password
A new pop-up window “Change password” will open, enter your current password then a new password, and then verify your new password and click on the “Change” button.
ROOT-пользователь — это пользователь с правами администратора, созданный по умолчанию в Linux-системе (Ubuntu). Root аналог администратору в ОС Windows, который имеет доступ ко всему в системе.
Этот способ предполагает вход в систему Ubuntu под пользователем с sudo правами, а команда «su» разрешена как часть «sudo» привилегий.
sudo su
Глядя на скриншот выше, можно заметить смену пользователя на «root», таким образом, мы вошли в Ubuntu под root, используя свой пароль.
Теперь мы можем сменить пароль root-пользователя, для этого необходимо использовать следующую команду:
passwd
После ввода команды указываем новый пароль в запросе «New password» и повторяем новый пароль после запроса «Retype new password».
Пароль для root будет установлен при первом использовании команды или изменит его на новый пароль при дальнейших использованиях команды «passwd».
А работает ли новый пароль? Давайте это выясним, нажимаем сочетание клавиш «Ctrl+D», чтобы окончить текущий ввод данных в терминале, либо запускаем новый терминал и вводим новую команду:
su
Данной командой мы войдем в систему как root, после чего вводим новый пароль, который мы только что установили для root.
Таким образом мы успешно изменили пароль от root.
Obviously it should be noted that these methods are valid for Ubuntu, Linux Mint and derivative distributions of both. All we will need is a working keyboard and familiarity with a few commands to fix this problem. As well we will have to have physical access to the equipmentas it cannot be solved remotely.
Table of Contents
Change lost or forgotten passwords in Ubuntu 17.10
Now we are going to see this method step by step.
We will turn off the PC.
After turning the computer on again and while it is in Grub, we will have to press the ‘e’ key. If you don’t see the Grub screen, then you probably only have Ubuntu installed on your machine. In such a case, Ubuntu does not boot into Grub to save time. But we will be able to access the menu we are looking for if hold down the SHIFT key during startup.
After pressing the ‘e’ key, the edit mode from the Grub boot menu. We are going to navigate with the arrow keys to the last lines.
At this point, we are going to edit text. That is why we will have to look for the line in which it says: ro quiet splash $vt_handoff.
Once the line is found, we will have to change the previous string to rw init = / bin / bash so that it is as shown in the previous screenshot.
The password is already changed and configured. Now we will restart typing (for example):
exec /sbin/init
First of all, I want to say that this method will help us to change passwords, but we will need to have the current root password at hand.
In this step we will have to restart the computer again.
At this point, among all the options we will have to choose the option ‘Advanced options for Ubuntu‘to go to the next screen.
Later, we can choose any of the lines in which we can read ‘Recovery Mode‘from the Grub menu.
This choice will show us a menu. In it, we will choose the ‘root’ option. This will take us to the terminal. This is where it will ask us for the current root password, so if we have forgotten it it is better to use method 1 to change it.
mount -rw -o remount /
passwd (nombre de usuario)
After all this, we can restart our computer and start using our new password.
If you are new to Ubuntu, you might want to know how to change password on your Ubuntu system using bash shell or command line.
Table of Contents
In order to carry out this process we need to use the command line in Ubuntu, so you can open one by looking for the terminal in your application menu or with the shortcut «Ctrl + Alt + T».
sudo -i
passwd
Now whenever you need to log in as root or perform any installation and configuration operations that require root authority, you are using this new password.
exit
sudo passwd root
When entering this command, it will ask them to enter the new password, once this has been done, it will ask for confirmation again and then proceed to make the changes,
As you can see, it is not necessary that you do it from root.
Now you possibly entered this article, thinking that the title referred to the recovery of a forgotten password.
Well, We will not leave that aside and we will explain a simple method for it.
To recover your root password, you must restart your computer. When this happens, after the BIOS screen of your computer passes, you will have to type the ESC or SHIFT key several times depending on the case.
Since depending on the BIOS you have, you may execute some action with ESC, so you must use shif, although you can search the network for some methods to access the Ubuntu Recovery mode.
Esto You have to do it so that the grub options are enabled, and being here you must select the start option that contains «Recovery mode» at the end.
Once this option is selected, you type Enter and it will begin to load the system, all good up to here. After a minute or so you should be on a screen with several options, including one that says «root».
You must position yourself in it with the help of the keyboard navigation dates and press Enter. Here you will be inside a console.
In it you can apply the same previous procedure that we explained to you to change the password, but first you must mount the root partition with:
mount -rw -o remount /
And then proceed to make your password change with:
passwd nombredeusuario
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:
passwd
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.
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>
If you changed your password and forgot it later, don’t worry. You can easily reset Ubuntu password.
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 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.
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.
More on user passwords in Linux
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.
Either you run commands with root privilege like this:
sudo any_command
sudo su
What is root user? Why is it locked in Ubuntu?
You don’t need to have root privilege for your daily tasks like moving file in your home directory, downloading files from internet, creating documents etc.
Take this analogy for understanding it better. If you have to cut a fruit, you use a kitchen knife. If you have to cut down a tree, you have to use a saw. Now, you may use the saw to cut fruits but that’s not wise, is it?
Does this mean that you cannot be root in Ubuntu or use the system with root privileges? No, you can still have root access with the help of ‘sudo’ (explained in the next section).
How to run commands as root user in Ubuntu?
apt update
Reading package lists... Done
E: Could not open lock file /var/lib/apt/lists/lock - open (13: Permission denied)
E: Unable to lock directory /var/lib/apt/lists/
W: Problem unlinking the file /var/cache/apt/pkgcache.bin - RemoveCaches (13: Permission denied)
W: Problem unlinking the file /var/cache/apt/srcpkgcache.bin - RemoveCaches (13: Permission denied)
So, how do you run commands as root? The simple answer is to add sudo before the commands that require to be run as root.
sudo apt update
[email protected]:~$ sudo apt update
[sudo] password for abhishek:
If you are absolutely new to Linux, you might be surprised that when you start typing your password in the terminal, nothing happens on the screen. This is perfectly normal because as the default security feature, nothing is displayed on the screen. Not even the asterisks (*). You type your password and press enter.
Bottom line:
To run commands as root in Ubuntu, add sudo before the command.
When asked for password, enter your account’s password.
When you type the password on the screen, nothing is visible. Just keep on typing the password and press enter.
How to become root user in Ubuntu?
The sudo command allows you to simulate a root login shell with this command:
sudo -i
[email protected]:~$ sudo -i
[sudo] password for abhishek:
[email protected]:~# whoami
root
[email protected]:~#
You’ll notice that when you switch to root, the shell command prompt changes from $ (dollar key sign) to # (pound key sign). This makes me crack a (lame) joke that pound is stronger than dollar.
sudo su
If you try to use the su command without sudo, you’ll encounter ‘su authentication failure’ error.
exit
How to enable root user in Ubuntu?
sudo passwd root
Again, this is not recommended and I won’t encourage you to do that on your desktop. If you forgot it, you won’t be able to change the root password in Ubuntu again.
sudo passwd -dl root
I hope you have a slightly better understanding of the root concept now. If you still have some confusion and questions about it, please let me know in the comments. I’ll try to answer your questions and might update the article as well.
Если вы новичок в Ubuntu, Возможно, вы захотите узнать, как изменить пароль в вашей системе Ubuntu, используя оболочку bash или командную строку.
В конце концов, изменение паролей для любого пользователя является хорошей практикой безопасности., особенно суперпользователя, который может выполнять все конфиденциальные операции в Ubuntu.
Только суперпользователь или root может изменить пароль любой учетной записи.. Другие пользователи могут изменять только свои пароли.
Пароли пользователей меняются в Ubuntu с помощью команды passwd. В этой статье мы объясним, как пользователь root может изменить свой пароль в Ubuntu.
Чтобы осуществить этот процесс нам нужно использовать командную строку в Ubuntu, поэтому вы можете открыть ее, выполнив поиск терминала в меню приложения или с помощью сочетания клавиш «Ctrl + Alt + T».
sudo -i
Система попросит вас ввести текущий пароль sudo. Это сделано, pЧтобы изменить пароль пользователя root, в терминале мы собираемся ввести следующую команду:
passwd
Когда они вводят команду passwd, система попросит вас ввести новый пароль для вашего пользователя root, затем система попросит вас повторно ввести новый пароль. После этого система подтвердит, что пароль обновлен правильно.
Как только этот процесс будет завершен, достаточно закрыть корневой сеанс, для этого в терминале мы должны ввести следующую команду:
exit
Но что происходит, когда вам нужно изменить пароль другого пользователя, если вы являетесь системным администратором.
Как изменить пароль другого пользователя в Ubuntu и производных?
Что ж, если вам нужно сменить пароль другого пользователя, вы можете сделать это аналогично предыдущему процессуТолько здесь необходимо указать имя пользователя, которому вы назначите новый пароль.
Вы можете сделать это с помощью следующей команды, В этом случае мы изменим пароль на root, хотя, как уже упоминалось, вы можете изменить пароль любого другого пользователя в системе:
sudo passwd root
При вводе этой команды он попросит их ввести новый пароль, как только это будет сделано, он снова запросит подтверждение, а затем продолжит вносить изменения,
Как видите, делать это от root необязательно.
Как восстановить пароль root?
Теперь вы, возможно, вошли в эту статью, думая, что заголовок относится к восстановлению забытого пароля.
Ну, Мы не будем оставлять это в стороне и объясним простой метод для этого.
Чтобы восстановить пароль root, необходимо перезагрузить компьютер. Когда это произойдет, после того, как экран BIOS вашего компьютера перейдет в разряд, вам придется нажимать клавишу ESC или SHIFT несколько раз в зависимости от случая.
Поскольку в зависимости от имеющейся у вас BIOS, вы можете выполнять некоторые действия с помощью ESC, поэтому вы должны использовать shift, хотя вы можете поискать в сети некоторые методы для доступа к режиму восстановления Ubuntu.
Эсто Вы должны сделать это так, чтобы были включены параметры grub, и, находясь здесь, вы должны выбрать параметр запуска, который в конце содержит «Режим восстановления».
Как только эта опция выбрана, вы вводите Enter, и она начинает загружать систему, все хорошо до этого момента. Через минуту или немного больше вы должны оказаться на экране с несколькими вариантами, в том числе с надписью «root».
Вы должны позиционировать себя в нем с помощью клавиатуры навигации по датам и нажать Enter. Здесь вы попадете в консоль.
В нем вы можете применить ту же предыдущую процедуру, которую мы объяснили вам, чтобы изменить пароль, но сначала вы должны смонтировать корневой раздел с помощью:
mount -rw -o remount /
А затем перейдите к изменению пароля с помощью:
passwd nombredeusuario
Наконец, в качестве дополнительного комментария, этот процесс может быть палкой о двух концах, поскольку кто-то неавторизованный может создать нового пользователя с правами администратора и получить доступ к вашей системе или изменить ваши учетные данные. В этом случае мне интересно, как мы можем отключить эту опцию?
Содержание статьи соответствует нашим принципам редакционная этика. Чтобы сообщить об ошибке, нажмите здесь.
Forgot your Ubuntu login password? It happens.
If you haven’t used Ubuntu for some time, it’s only natural to not remember the password. The good news is that you don’t need to reinstall the entire operating system because of it. You can recover Ubuntu passwords easily.
The method mentioned here works for resetting an Ubuntu password in VMware, dual boot or single install. All you need is a little bit of patience and to run a couple of commands. You’ll reset the root password within minutes.
Reset Ubuntu password from recovery mode
Step 1: Boot into recovery mode
Switch the computer on. Go to the grub menu. Generally, it appears automatically – if not, then hold down the shift key or press Esc key until the boot menu appears.
If you’re using Oracle VirtualBox or VMware, you have to hold down the shift key when the logo of Oracle or VMware appears.
In the grub menu, select the “Advanced Options for Ubuntu”:
In here, you’ll see the option to go to recovery mode:
It will bring you to a black screen with several lines of output being displayed in a flash. Wait for a few seconds here.
Step 2: Drop to root shell prompt
Now you’ll be presented with different options for recovery mode. Here you need to choose “Root – Drop to root shell prompt“. Just press the enter key to select this option. Like in the picture below:
You’ll see that when you select the root shell prompt option, an option to enter commands appears at the bottom. This is your root shell prompt and this is where you’ll use the commands to reset the password.
Step 3: Remount the root with write access
You need to have write access to the root partition. By default, it has read-only access.
Use the command below to remount it with write access:
mount -rw -o remount /
Step 4: Reset username or password
ls /home
passwd username
It prompts for a new password. Enter the new password twice.
Do note that nothing is displayed on the screen when you start typing the password. This is perfectly normal and actually a security feature in Linux systems. Just blindly type the password and press enter.
Enter new UNIX password:
Retype new UNIX password:
Voilà! There you go. You have just successfully reset the password. Now exit the root shell prompt:
exit
When you exit, you’ll be back at the recovery mode menu. Select the normal boot option here.
There will be a warning about graphics mode compatibility. Don’t worry. A complete reboot will fix any issues with this.
You should now be able to log in with the new password.
Possible Troubleshoot:
While entering the new password you might be prompted with Authentication token manipulation error like this:
mount -rw -o remount /
Now try to reset the password again. It should work now.
As you can see, it is extremely easy to change Ubuntu password even if you’ve forgotten it. It will barely take a few minutes.
Alternate method to reset Ubuntu password
If for some reason you have difficulty dropping to the root shell and changing the password, you can try these steps.
Step 1
Reboot your computer. Hold shift to bring up the grub screen (if it doesn’t appear automatically). Press E at the grub prompt to edit the grub screen.
Step 2
Find the line starting with linux, change the ro to rw and append init=/bin/bash at the end of that line.
Step 3
Press ctrl-x to save your changes and boot.
In other words, your system will boot up to a passwordless root shell.
Step 4
Set your new password.
Once you’ve set the new password, exit the terminal. Just type reboot in the terminal or use the shutdown command.
shutdown -r now
Your password should be changed now.
If resetting Ubuntu passwords is this easy, isn’t this a security risk?
That’s a fair question. One of the main advantages of Linux over Windows is its security. But if “anyone” can reset the password, how come Ubuntu or other Linux distributions can be considered secure?
Let me explain a few things here. The main security risk is if someone hacks into your account from a remote location via the internet. That’s not happening here.
If anyone has physical access to your computer, the data in your computer is already at risk. Unless the entire disk is encrypted, anyone can “steal” your data using a live USB without even entering your installed operating system.
This lack of root password is a deliberate feature The “advanced options for Ubuntu” in the boot menu allow you to perform some specific root-related tasks from the “root shell prompt”. This is why you’re able to reset the Ubuntu password through this method.
Bonus Tip: Handling the possible keyring issue after changing the password
There is a keyring feature in Ubuntu that is used for keeping passwords locked and safe.
When you reset the forgotten password, the keyring remains unlocked and you may see an error message like this.
Open the Passwords and Keys application and here, delete the Login passwords.
When you try to use Google Chrome again in Ubuntu, it will ask you to create a new keyring. Use the new login password as the keyring password.
Did it help you?
I hope I made things clear about resetting forgotten passwords in Ubuntu.
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.
Change the password for your own account
Just enter the command passwd
:
passwd
It asks for the current password. Enter this password.
You probably already know that the Linux terminals show nothing on the screen while you type the password.
Enter the password correctly, and it will ask you to enter the new password twice. You should see the success message if you successfully type the new password twice.
[email protected]:~$ passwd
Changing password for abhishek.
Current password:
New password:
Retype new password:
passwd: password updated successfully
That’s it. That’s how you change passwords in the Ubuntu command line.
Сбрасываем пароль от root через GRUB
Существует еще один способ для изменения пароля от root или любого другого пользователя при загрузке Ubuntu.
Сначала перезагружаем наш ПК. Если меню GRUB не появляется автоматически, то удерживаем клавишу «Shift» во время загрузки. Это принудительно откроет меню GRUB.
Затем выбираем пункт «Ubuntu» в меню и нажмите клавишу «E», чтобы начать редактирование конфигурации загрузки.
Далее необходимо внести изменения в строку, заменяем значение:
quiet splash $vt_handoff
rw init=/bin/bash
Результат отображен на скриншоте ниже:
Изменения заключаются в том, чтобы из GUI перейти в оболочку Bash для внесения изменений — смена пароля. Нажимаем клавишу «F10», чтобы загрузиться с новой конфигурацией.
Загрузка с измененной конфигурацией сработает только один раз и сброситься при повторной загрузке.
Мы вошли в систему как root-пользователь в командной строке. Теперь используем команду для сброса пароля:
passwd
Указываем и повторяем новый пароль.
Затем перезагружаем систему в обычном режиме (без GRUB) и входим как root уже с новым паролем.
Log in as root user
@ sudo -i
The system will prompt you to enter the current sudo password. Please enter the password and hit Enter.
Run a command as another user
su -c command_to_run user_name
The command should be a single argument and hence you should keep it under quotes.
[email protected]:/home/abhishek# su -c "touch a.txt" abhishek
[email protected]:/home/abhishek# ls -l a.txt
-rw-rw-r-- 1 abhishek abhishek 0 Aug 23 07:56 a.txt
[email protected]:/home/abhishek#
I hope you like this handy Ubuntu tutorial.
Subscribe
Join the newsletter to get the latest updates.
Switch to root user
su
When asked, enter the root password:
[email protected]:/root$ su
Password:
[email protected]:~#
sudo su
When asked for the password, enter your account’s password:
[email protected]:~$ sudo su
[sudo] password for abhi:
[email protected]:/home/abhi#
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
An Alternative
$ sudo passwd root
When you enter the above command, the system will prompt you to enter the new UNIX root password. When you enter the new password and hit enter, the system will prompt you to retype the new UNIX root password. After doing so, the system will confirm that the password is updated successfully.
With the help of this article, you can change the password for sudo and make your system secure from any malicious activity time and again.
Open the Ubuntu command line
We need to use the Ubuntu command line, the Terminal, in order to change the sudo password. Open the Terminal either through the system Dash or the Ctrl+Alt+T shortcut.
Switching users into their login shell
su -l other_username
You can use -p
option instead of -l
to preserve the environment instead of testing them in the new shell.
Resetting the root password
Step 1: Booting to Recovery
This is the boot menu for Ubuntu that has different kernel versions that are displayed and has different options. Select the option Ubuntu by pressing the <enter> key. When you selected Ubuntu, you need to press the “e” key to open up the grub parameters that are to be edited.
Step 2: Changing the configurations
After that use arrow keys again and then scroll down further to the bottom line that begins with “linux /boot/vmlinuz” keyword.
From the above-highlighted line, you need to replace “ro quiet splash $vt_handoff” word with “rw init=/bin/bash”.
Step 3: Rebooting the system
The next step is to reboot your system. This will be done by using the Ctrl + X or by using the F10 key. It will help you to reboot the system along with the updates you made in your system. The system will restart and then you will be landed to your root shell of the system. The shell will appear only one-time and in future, it will appear normally.
$ mount | grep -w /
Step 4: Changing the root password
$ passwd
After that, the system will prompt you to type the new password and once you have pressed the enter key, it will again ask you to re-type the password.
Once the password is updated, a success message will appear on the screen.
The password is now changed/rest successfully. To confirm the updates, you can restart your system.
Change password for other user accounts
sudo passwd username
[email protected]:~# passwd abhi
New password:
Retype new password:
passwd: password updated successfully
That’s it. Short, sweet, and simple. Enjoy Ubuntu!
Subscribe
Join the newsletter to get the latest updates.
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
Get Temporary root access through the sudo command
$ sudo nano adduser.conf
Change the sudo password through the passwd command
$ passwd
When you enter the passwd command, the system will prompt you to enter the new UNIX root password. When you enter the new password and hit enter, the system will prompt you to retype the new UNIX root password. After doing so, the system will confirm that the password is updated successfully.
Now whenever you need to log in as root or perform any installation and configuration operation that requires root authorization, you will be using this new password.
Changing the root password
$ sudo passwd root
When you will press the <enter> key from the keyboard, the password will then be updated successfully.
Switch to another user from a regular user
su other_username
sudo su other_username
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
Switching to a normal user from root user
su other_username
exit
Exit the root login and then the Terminal
$ exit
Once you are logged out, type the exit command again to exit the Terminal application.