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 密碼重置圖文教學(單用戶模式)

編輯:Linux 教學

遺失 Root 密碼時,透過 GRUB 進入單用戶模式(Single User Mode / Emergency Mode)即可無舊密碼重置。本文以 CentOS 7 / RHEL 7 為例,提供完整圖文步驟。

適用版本

  • CentOS 6/7/8、RHEL 6/7/8、Oracle Linux、Rocky/AlmaLinux
  • GRUB 2(主流版本);GRUB Legacy 步驟略有不同,文末補充。

操作流程

1. 重啟並進入 GRUB 選單

開機時於 GRUB 計數器歸零前按任意鍵(通常是 ↑/↓ 或 Space),停在選單畫面。

GRUB 選單畫面
GRUB 開機選單

2. 編輯開機項目

  1. 用方向鍵選中預設開機項(通常是第一或第二行)。
  2. 按 e 進入編輯模式。
GRUB 編輯畫面
選中 kernel 行並按 e 編輯

3. 修改 kernel 參數

  1. 找到以 linux16 / linuxefi 開頭的那一行(kernel 命令列)。
  2. 游標移至行末,加入 rd.break(CentOS 7/RHEL 7)或 single / init=/bin/bash(CentOS 6)。
  3. 範例(CentOS 7):
linux16 /vmlinuz-3.10.0-1160.el7.x86_64 root=/dev/mapper/centos-root ro crashkernel=auto rd.lvm.lv=centos/root rd.lvm.lv=centos/swap rhgb quiet rd.break
加入 rd.break
在 kernel 行末加入 rd.break

4. 以單用戶模式啟動

  • 按 Ctrl+x(或 F10)啟動。
  • 系統將掛載 /sysroot 並進入 sh 提示符。
單用戶模式提示符
進入 emergency shell

5. 重新掛載根分區為讀寫

# mount -o remount,rw /sysroot

6. 切換根環境並改密碼

# chroot /sysroot
# passwd root
Changing password for user root.
New password: 
Retype new password: 
passwd: all authentication tokens updated successfully.
passwd 成功
Root 密碼重置成功

7. 關鍵:重設 SELinux 標籤

因在 chroot 外修改 /etc/shadow,SELinux 上下文會錯誤,必須:

# touch /.autorelabel
# exit          # 離開 chroot
# exit          # 離開 emergency shell,系統將自動重新標籤並重啟

8. 等待重新標籤完成

重啟過程中會跑 SELinux relabeling,耗時視磁碟大小而定(通常 1-5 分鐘),完成後即可用新密碼登入。

GRUB Legacy(CentOS 5/6 舊版)快速版

# GRUB 選單按 e 編輯 kernel 行
# 行末加 single 或 1
# 按 b 啟動
# 進入單用戶模式後:
mount -o remount,rw /
passwd root
touch /.autorelabel
reboot

常見問題

問題原因解決
改完密碼登入仍失敗SELinux 標籤錯誤務必 touch /.autorelabel 並等待重啟完成
進入 emergency shell 但無 /sysrootLVM/RAID 未啟動手動 vgchange -ay、mount /dev/mapper/... /sysroot
雲端主機無法進 GRUB主控台不同使用 VNC 主控台、或透過救援模式 ISO 掛載磁碟修改
忘記加 rd.break 直接啟動正常多用戶模式重啟再試一次

安全性提醒

  • 物理/主控台存取即可繞過 Root 密碼,實體安全是第一道防線。
  • 生產環境建議:GRUB_PASSWORD 加密保護開機選單、BIOS/UEFI 設定密碼、機櫃上鎖。
  • 雲端主機啟用「救援模式」或「串列主控台」作為備用入口。
單用戶模式重置密碼是 Linux 系統管理員必備技能。記住 rd.break → remount rw → chroot → passwd → /.autorelabel → reboot 七步曲,關鍵在 SELinux 重標籤,否則新密碼雖設定成功卻無法登入。
Copyright © Windows教程網 All Rights Reserved