遺忘 Root 密碼是運維常見場景。CentOS 7(systemd 架構)與舊版 SysV init 的單用戶模式進入方式截然不同。本文提供圖文級步驟,涵蓋 GRUB2 編輯、內核參數注入、SELinux 重標記、運行等級對照表,並延伸至 yum 升級、桌面安裝等實操技巧。
cat /etc/redhat-release # 如 CentOS Linux release 7.9.2009
uname -r # 核心版本,如 3.10.0-1160.el7.x86_64
uname -m # 架構:x86_64
getconf LONG_BIT # 32/64 位元確認
linux16 / linuxefi 開頭的那一行(最長的那行)。rd.break(推薦)或 1 / single / init=/bin/bash。/sysroot 為唯讀)。# 1. 重新掛載 /sysroot 為讀寫
mount -o remount,rw /sysroot
# 2. 切換根目錄
chroot /sysroot
# 3. 修改 root 密碼
passwd root
# 輸入新密碼兩次
# 4. 關鍵:觸發 SELinux 重標記(否則下次開機會因標籤錯誤拒絕登入)
touch /.autorelabel
# 5. 退出 chroot 並重啟
exit
exit # 或 reboot
系統重啟時會執行完整 SELinux 重標記(可能耗時數分鐘),隨後即可用新密碼登入。
| 等級 | SysV 含義 | Systemd Target | 用途 |
|---|---|---|---|
| 0 | 關機 | poweroff.target | 關機 |
| 1 | 單用戶/維護 | rescue.target | 密碼重修、檔案系統修復 |
| 2 | 多用戶無網路 | multi-user.target | 極少用 |
| 3 | 多用戶命令列 | multi-user.target | 伺服器預設(無 GUI) |
| 4 | 保留/自訂 | — | — |
| 5 | 多用戶圖形界面 | graphical.target | 桌面環境 |
| 6 | 重啟 | reboot.target | 重啟 |
# 臨時切換(不持久)
systemctl isolate multi-user.target # 文字模式
systemctl isolate graphical.target # 圖形模式
systemctl isolate rescue.target # 單用戶/維護
# 永久修改預設目標
systemctl set-default multi-user.target
systemctl set-default graphical.target
# 查看當前/預設目標
systemctl get-default
runlevel # 顯示 N 3 等傳統格式
# 系統更新(生產環境建議先備份/快照)
yum update -y
# 查看可用套件群組
yum grouplist
yum groupinfo "Server with GUI"
# 安裝桌面環境(GNOME)
yum groupinstall "Server with GUI" -y
# 或最小桌面
yum groupinstall "GNOME Desktop" "Graphical Administration Tools" -y
# 啟動圖形介面
systemctl set-default graphical.target
reboot
# 或臨時啟動
startx
yum update 直接跑:核心升級可能導致第三方驅動(RAID、GPU、虛擬化)失效,務必先在測試機驗證。systemctl start network 或 nmcli con up eth0。touch /.autorelabel 是救命稻草,否則重啟後 login 直接失敗。grub2-setpassword 設定開機編輯密碼,防止物理接觸者重置 Root 密碼。CentOS 7 破解密碼核心在於 rd.break + chroot /sysroot + touch /.autorelabel 三步走。熟練 Systemd 目標單元操作(systemctl isolate/set-default/get-default),即可靈活在文字、圖形、維護模式間切換,配合謹慎的 YUM 更新策略,讓伺服器穩健可控。