找回密码

Ubuntu

如果你在 Ubuntu 22.04 系统中忘记了密码,可以按照以下步骤重置密码:

方法 1:通过恢复模式(Recovery Mode)

  1. 重启计算机:启动时,按住 Shift 键(有时是 Esc 键),进入 GRUB 菜单。
  2. 选择恢复模式:在 GRUB 菜单中,选择带有 (Recovery Mode) 字样的内核版本。
  3. 进入Root Shell:在恢复模式菜单中,选择 root - Drop to root shell prompt
  4. 挂载根文件系统(一般可不用执行):执行以下命令将根文件系统以读写模式挂载:
    mount -o remount,rw /
  5. 重置密码:使用 passwd 命令重置所需用户的密码。例如,要重置 username 的密码:
    passwd username
    然后按照提示输入新的密码。
  6. 重启系统:重置密码后,输入以下命令重启系统:
    reboot

方法 2:通过Live USB

  1. 创建Live USB:使用Ubuntu安装镜像制作一个Live USB。
  2. 启动Live USB:从Live USB启动计算机,选择“Try Ubuntu”。
  3. 挂载根文件系统:打开终端,使用以下命令找到并挂载你原本的根文件系统:
    sudo fdisk -l
    sudo mount /dev/sdXn /mnt
    (其中 sdXn 代表你安装 Ubuntu 的分区,可能是 /dev/sda1/dev/nvme0n1p1,视情况而定)
  4. 重置密码
    sudo chroot /mnt
    passwd username
    输入新密码后,退出 chroot 环境:
    exit
    sudo umount /mnt
  5. 重启系统:输入以下命令重启系统:
    sudo reboot

CentOS

方法一

# 启动时任意键暂停启动
# 按e键进入编辑模式
# 将光标移动linux 开始的行,添加内核参数rd.break
# 按ctrl-x启动
mount –o remount,rw /sysroot
chroot /sysroot
passwd root
# 如果SELinux是启用的,才需要执行下面操作,如查没有启动,不需要执行
touch /.autorelabel
exit
reboot

方法二

# 启动时任意键暂停启动
# 按e键进入编辑模式
# 将光标移动linux 开始的行,改为rw init=/sysroot/bin/sh
# 按ctrl-x启动
chroot /sysroot
passwd root
# 如果SELinux是启用的,才需要执行下面操作,如查没有启动,不需要执行
touch /.autorelabel
exit
reboot

# 为了防止轻易破解root密码,可以选择给GRUB2添加口令:

# 添加grub密码
[root@centos8 ~]#grub2-setpassword

# 清空grub密码
[root@centos8 ~]#cat /dev/null > /boot/grub2/user.cfg | rm -f /boot/grub2/user.cfg (看好文件,别写错)