Red Hat 系列 (RHEL、CentOS、Rocky、Alma、Fedora) 經歷了 SysV init (/etc/rc.d/rc.local) 到 systemd 的演進。本文系統梳理三大自動執行觸發點:開機啟動、使用者登入、使用者登出,對比傳統與現代做法,提供生產環境最佳實踐。
# 1. 確保腳本可執行
chmod +x /etc/rc.d/rc.local
# 2. 編輯檔案,在 exit 0 之前加入指令
vi /etc/rc.d/rc.local
# 範例:掛載遠端儲存、啟動自訂服務、設定核心參數
/usr/bin/mount -t nfs nas:/data /mnt/data
echo never > /sys/kernel/mm/transparent_hugepage/enabled
/opt/myapp/bin/start.sh
# 3. systemd 會自動偵測並啟用 rc-local 服務
systemctl status rc-local
缺點:無相依性管理、無並行啟動、無日誌整合、難以除錯、不支援條件式啟動。
建立 /etc/systemd/system/myapp.service:
[Unit]
Description=My Custom Application
Documentation=man:myapp(1)
After=network-online.target nfs-client.target
Wants=network-online.target
ConditionPathExists=/opt/myapp/bin/start.sh
[Service]
Type=simple
ExecStartPre=/usr/bin/mount -t nfs nas:/data /mnt/data
ExecStart=/opt/myapp/bin/start.sh
ExecStop=/opt/myapp/bin/stop.sh
Restart=on-failure
RestartSec=10
User=myapp
Group=myapp
# 安全強化
NoNewPrivileges=yes
PrivateTmp=yes
ProtectSystem=strict
ProtectHome=yes
ReadWritePaths=/mnt/data /var/log/myapp
CapabilityBoundingSet=CAP_NET_BIND_SERVICE
AmbientCapabilities=CAP_NET_BIND_SERVICE
[Install]
WantedBy=multi-user.target
啟用:systemctl daemon-reload; systemctl enable --now myapp
/etc/sysctl.d/99-custom.conf:net.ipv4.tcp_fastopen=3,systemd-sysctl 開機自動套用。/etc/modules-load.d/custom.conf:br_netfilter, vfio_pci,systemd-modules-load 開機載入。| 檔案 | 登入 Shell | 互動式非登入 Shell | 非互動式 Shell (腳本) | 優先級/備註 |
|---|---|---|---|---|
| /etc/profile | ✅ 讀取 | ❌ | ❌ | 系統級環境變數、PATH、umask |
| /etc/profile.d/*.sh | ✅ 由 profile 迴圈載入 | ❌ | ❌ | 模組化設定 (如 java.sh, docker.sh) |
| ~/.bash_profile | ✅ 優先級 1 | ❌ | ❌ | 存在即讀取,忽略下兩者 |
| ~/.bash_login | ✅ 優先級 2 | ❌ | ❌ | 無 .bash_profile 時讀取 |
| ~/.profile | ✅ 優先級 3 | ❌ | ❌ | POSIX 標準,sh/bash 通用 |
| ~/.bashrc | ❌ (通常由 profile source) | ✅ 讀取 | ❌ | 互動式設定:alias、prompt、函式、歷史控制 |
| ~/.bash_logout | 登出時讀取 | ❌ | ❌ | 清理暫存、備份、記錄 |
# /etc/profile.d/custom.sh (系統級,所有使用者)
export JAVA_HOME=/usr/lib/jvm/java-21
export PATH=$JAVA_HOME/bin:$PATH
export EDITOR=vim
umask 027
# ~/.bashrc (使用者互動式)
# 避免重複 source
[[ $- != *i* ]] && return
alias ll='ls -alF --color=auto'
alias grep='grep --color=auto'
alias ..='cd ..'
alias ...='cd ../..'
# 歷史優化
HISTSIZE=10000
HISTFILESIZE=20000
HISTCONTROL=ignoreboth:erasedups
shopt -s histappend
PROMPT_COMMAND="history -a; $PROMPT_COMMAND"
/etc/environment:PAM pam_env.so 讀取,影響所有 PAM 登入 (含圖形、SSH、su)。純 KEY=VAL 格式,無 export、無變數展開。/etc/xprofile / ~/.xprofile:Xsession 腳本載入 (部分顯示管理器支援)。~/.config/environment.d/*.conf:systemd --user 環境變數 (systemd 250+)。# 範例:備份程式碼、清理暫存、記錄登出時間
tar -czf ~/backups/src-$(date +%F).tar.gz ~/src/*.c 2>/dev/null
rm -rf ~/.cache/tmp-*
echo "$(date): User $USER logged out from $SSH_TTY" >> ~/login.log
使用者級 systemd 服務可在登入時啟動、登出時停止:
# ~/.config/systemd/user/backup.service
[Unit]
Description=Auto Backup on Logout
DefaultDependencies=no
Before=shutdown.target
[Service]
Type=oneshot
ExecStart=/usr/bin/tar -czf ~/backups/src-$(date +%%F).tar.gz ~/src/*.c
RemainAfterExit=yes
[Install]
WantedBy=shutdown.target
systemctl --user daemon-reload
systemctl --user enable --now backup.service
loginctl enable-linger $USER # 允許使用者服務在無登入時運行 (可選)
| 特性 | cron | systemd timer |
|---|---|---|
| 精度 | 分鐘級 | 秒級 |
| 日誌整合 | syslog/mail | journalctl 統一查詢 |
| 相依性/順序 | 無 | 支援 After/Requires/Wants |
| 錯誤處理/重試 | 無 | Restart=, RestartSec= |
| 隨機化延遲 | 無 | RandomizedDelaySec= |
| 持久化 (開機補跑) | anacron | Persistent=true |
建議:系統級定時任務優先使用 systemd timer;使用者級簡單排程可用 crontab -e。
自動化執行的核心在於宣告式、可觀測、可復原。拋棄脆弱的 rc.local 與散落的 Shell 腳本,擁抱 systemd Unit 的結構化定義,讓開機、登入、登出、排程的每一個自動化動作都納入版控、監控與測試體系,這才是現代 Linux 運維的專業標準。