萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

Linux 忘記 Root 密碼?單用戶模式 / GRUB 急救模式快速重置指南

適用場景

  • Root 密碼遺失、過期或被惡意修改。
  • sudo 權限用戶亦不可用。
  • 實體/虛擬機主機板可重啟並進入 GRUB 選單。

方法一:GRUB 進入單用戶模式 (SysVinit / systemd 通用)

  1. 重啟系統,在 GRUB 選單出現時按 Esc (或 Shift) 進入選單。
  2. 選中預設啟動項,按 e 編輯。
  3. 找到以 linux 或 linux16 / linuxefi 開頭的行,行尾加入:
    rd.break (RHEL/CentOS 7/8) 或 systemd.unit=emergency.target (systemd 通用) 或 single / init=/bin/bash (傳統)。
  4. 按 Ctrl+x 或 F10 啟動。

進入急救環境後的關鍵步驟

# 1. 掛載根檔案系統為讀寫 (rd.break 進入的 initramfs 環境)
mount -o remount,rw /sysroot
chroot /sysroot

# 2. 修改密碼
passwd root
# 輸入新密碼兩次

# 3. 關鍵:重設 SELinux 標籤 (否則下次開機無法登入)
touch /.autorelabel

# 4. 退出並重啟
exit
mount -o remount,ro /sysroot
reboot

方法二:GRUB 直接進入 Bash (最快、最暴力)

  1. GRUB 編輯模式 (e),在 linux 行尾加入:
    init=/bin/bash
  2. Ctrl+x 啟動,直接進入 root shell (根分區已掛載為唯讀)。
  3. 執行:
mount -o remount,rw /
passwd root
touch /.autorelabel
exec /sbin/init   # 或 reboot -f

方法三:LiveCD / 救援光碟 (通用、不依賴 GRUB)

  1. 啟動 LiveCD (Ubuntu Desktop、SystemRescue、Finnix 等)。
  2. 掛載目標根分區:
mkdir /mnt/target
mount /dev/sda2 /mnt/target   # 視實際分區調整
# 若有獨立 /boot、/var、/home 等需一併掛載
mount /dev/sda1 /mnt/target/boot
  1. chroot 進入:
mount --bind /dev /mnt/target/dev
mount --bind /proc /mnt/target/proc
mount --bind /sys /mnt/target/sys
chroot /mnt/target

passwd root
touch /.autorelabel
exit
reboot

雲端虛擬機特殊處理

  • AWS EC2:脫機掛載根磁碟到另一實例修改 /etc/shadow,或用 Systems Manager Session Manager 重置。
  • Azure VM:使用「重設密碼」擴充功能或 Serial Console。
  • GCP:串列主控台或掛載磁碟到新 VM。
  • 阿里雲/騰訊雲:控制台「重置密碼」功能 (需重啟)。

SELinux 重標記原理解析

touch /.autorelabel 會在下次開機觸發 restorecon -R /,將所有檔案安全上下文恢復為政策預設值。若跳過此步驟,新密碼在 /etc/shadow 的標籤錯誤,導致登入失敗 (audit.log 會記錄 type=AVC 拒絕)。

預防措施

  • 設定 GRUB 密碼防止惡意編輯啟動參數:
    grub2-setpassword (RHEL) / grub-mkpasswd-pbkdf2 + /etc/grub.d/40_custom。
  • 使用 SSH 金鑰登入 + 禁用密碼登入 (PasswordAuthentication no)。
  • 建立 sudo 權限的備用管理員帳號。
  • 定期備份 /etc/shadow、/etc/sudoers。
copyright © 萬盛學電腦網 all rights reserved