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

CentOS 5/6/7 根密碼遺忘?單用戶模式與救援模式雙重破解實戰

編輯:Linux 教學

根密碼遺忘是 Linux 運維的經典場景。本文提供兩種通用、安全、無損的破解方案:GRUB 單用戶模式(適用於主機台可操作)與 光碟救援模式(適用於遠端/無法進入 GRUB),覆蓋 CentOS 5/6/7 全系列,助你在 5 分鐘內重獲系統控制權。

方案一:GRUB 單用戶模式(推薦,最快)

適用:實體機/虛擬機主機台可見、GRUB 選單未加密、未啟用全盤加密。

CentOS 5/6 (GRUB Legacy)

  1. 開機進入 GRUB 選單,按 e 編輯啟動項
  2. 選中 kernel 行,再按 e,在行尾添加 single 或 1 或 rd.break(CentOS 6)
  3. 按 Enter 返回,按 b 啟動,進入單用戶 Shell(無需密碼)
  4. 執行密碼重置:
    # 重掛根分區為讀寫(關鍵步驟)
    mount -o remount,rw /
    
    # 修改密碼
    passwd root
    # 或直接清空 /etc/shadow 中 root 的密碼欄位
    # vi /etc/shadow  →  root::...  (保留冒號)
    
    # 重建 SELinux 標籤(如啟用 SELinux)
    touch /.autorelabel
    
    reboot

CentOS 7 (GRUB2)

  1. GRUB 選單按 e 編輯啟動項
  2. 找到 linux16 /vmlinuz-... 行,行尾添加 rd.break
  3. Ctrl+x 啟動,進入 switch_root 環境
  4. 執行:
    mount -o remount,rw /sysroot
    chroot /sysroot
    passwd root
    touch /.autorelabel
    exit
    reboot

方案二:光碟/ISO 救援模式(通用,最穩)

適用:GRUB 損壞、主機台不可操作(如雲主機 VNC)、單用戶模式需密碼(如設定了 sulogin)、LUKS 加密分區。

  1. 掛載 CentOS 安裝 ISO,開機選擇 Troubleshooting → Rescue a CentOS system
  2. 選擇語言/鍵盤,系統會自動掃描並掛載根分區至 /mnt/sysimage
  3. 進入 Shell 環境:
# 切換到系統根環境
chroot /mnt/sysimage

# 修改密碼
passwd root

# 若 /etc/shadow 權限導致無法存檔
chmod 644 /etc/shadow  # 臨時放寬
vi /etc/shadow         # 清空 root 密碼欄
chmod 400 /etc/shadow  # 恢復權限

# SELinux 重打標
touch /.autorelabel

exit
reboot

避坑指南與最佳實踐

  • GRUB 加密:生產環境建議設定 GRUB 密碼(grub2-setpassword),防止單用戶模式被濫用,但務必妥善保管 GRUB 密碼!
  • SELinux:修改密碼後務必 touch /.autorelabel,否則重啟後可能因標籤錯誤導致登入失敗或服務異常。
  • LUKS 加密:若根分區加密,單用戶模式需先 cryptsetup luksOpen 解密,救援模式同理。
  • 雲主機:AWS/Azure/GCP 等雲平台提供「重置密碼」或「掛載救援磁碟」功能,優先使用平台原生工具。
  • 事後審計:重置密碼後,檢查 /var/log/secure、last、lastb 確認無異常登入,並立即更換為高強度密碼、配置 SSH 金鑰認證、禁用密碼登入。

總結

單用戶模式快捷輕量,救援模式通用性強。熟練掌握雙方案,並結合 GRUB 加密、SELinux 管理、雲平台原生工具,即可從容應對各類密碼遺忘與啟動故障,將停機時間壓縮到分鐘級。

Copyright © Windows教程網 All Rights Reserved