Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> 關於 Linux

Linux 忘記 root 密碼?單用戶模式 / GRUB2 急救模式 重置全流程

編輯:關於 Linux

Root 密碼遺忘是 Linux 運維必遇場景。現代發行版 (CentOS 7/8, RHEL 7/8, Ubuntu 18.04+, Debian 9+) 均使用 GRUB2,重置流程統一為:中斷 GRUB → 編輯內核參數進入急救模式 → 重掛載根分區讀寫 → 修改密碼 → 重啟。本文提供通用 GRUB2 流程、舊版 GRUB Legacy 流程、SELinux 重標記、關鍵故障排查。

一、GRUB2 通用重置流程 (適用主流發行版)

1. 重啟並進入 GRUB 菜單

  • BIOS 啟動:開機按住 Shift (或反複按 Esc)。
  • UEFI 啟動:開機反複按 Esc 或 F12 進入 Firmware 菜單選擇 GRUB。

2. 編輯啟動參數

  • 方向鍵選中默認內核行,按 e 進入編輯模式。
  • 找以 linux / linuxefi / linux16 開頭的行 (內核參數行)。
  • 行尾追加:rd.break (RHEL/CentOS/Fedora) 或 init=/bin/bash (Debian/Ubuntu/通用)。
  • 按 Ctrl+x 或 F10 啟動。

3. 進入急救環境後操作


# --- 方案 A: rd.break (RHEL 系) ---
# 系統掛載真實根分區到 /sysroot,且為只讀
mount -o remount,rw /sysroot
chroot /sysroot
passwd root
# 輸入新密碼兩次
touch /.autorelabel  # 關鍵!SELinux 重標記,防止下次啟動卡住/拒絕登錄
exit
mount -o remount,ro /sysroot
reboot

# --- 方案 B: init=/bin/bash (Debian/Ubuntu/通用) ---
# 直接進入根 Shell,根分區通常只讀
mount -o remount,rw /
passwd root
# 若啟用 SELinux (Ubuntu 默認不啟用,CentOS 默認啟用)
touch /.autorelabel
sync
reboot -f  # 或 exec /sbin/init

二、GRUB Legacy (CentOS 6 等舊版) 流程


# 1. 開機按任意鍵進入 GRUB 菜單
# 2. 選中內核,按 e 編輯
# 3. 選中 kernel 行,按 e
# 4. 行尾加 single 或 1 (運行級別 1)
# 5. 按 Enter,再按 b 啟動
# 6. 進入單用戶模式 (無需密碼)
# 7. passwd root
# 8. reboot

三、關鍵細節與避坑

1. SELinux 重標記 (.autorelabel) 必不可少

  • 修改 /etc/shadow 後,文件安全上下文可能不匹配策略,導致登錄失敗、啟動卡在 "SELinux policy"。
  • touch /.autorelabel 會在下次啟動觸發全盤重標記 (耗時數分鐘),務必執行。
  • 若忘記,可再次進入急救模式執行 restorecon -Rv /etc/shadow 或 autorelabel。

2. 根分區掛載點確認

  • rd.break:真實根在 /sysroot,需 chroot /sysroot。
  • init=/bin/bash:真實根在 /,直接操作。
  • 使用 lsblk -f、findmnt 確認掛載情況。

3. LVM / 加密分區 (LUKS) 場景

  • LVM:rd.break 通常已自動激活 VG/LV,掛載至 /sysroot。
  • LUKS:需在 GRUB 參數添加 rd.luks.uuid=UUID,或進入急救模式後手動 cryptsetup open /dev/sda2 root、vgchange -ay、mount /dev/mapper/vg-root /sysroot。

4. 若 root 賬戶被鎖定 (passwd -l root / /etc/shadow 以 ! 開頭)


passwd -u root  # 解鎖
passwd root     # 重設密碼

5. 使用 LiveCD/ISO 救援模式 (通用終極大招)


# 1. 掛載系統根分區
mount /dev/sda2 /mnt
# 若有單獨 /boot: mount /dev/sda1 /mnt/boot
# 若 LVM: vgchange -ay; mount /dev/mapper/vg-root /mnt
# 2. chroot 進入
chroot /mnt
# 3. 修改密碼、修復 GRUB、檢查 fstab 等
passwd root
# 4. 退出重啟
exit
reboot

四、預防措施

  • 使用密碼管理器 (Bitwarden, 1Password, KeePass) 存儲 root 密碼。
  • 禁用 root 遠程登錄 (PermitRootLogin no),普通用戶 sudo 提權。
  • 配置 SSH 金鑰認證,禁用密碼認證 (PasswordAuthentication no)。
  • 設置 GRUB 密碼 (grub2-setpassword) 防止惡意進入單用戶模式。

五、總結

忘記 root 密碼不恐慌。GRUB2 + rd.break/init=/bin/bash + chroot + passwd + .autorelabel 是現代 Linux 通用解法。熟練掌握 GRUB 編輯、掛載點識別、SELinux 重標記、LVM/LUKS 處理,能應對 99% 密碼重置場景。

GRUB2 編輯內核參數重置 root 密碼流程圖

Copyright © Windows教程網 All Rights Reserved