萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 作業系統 >  >> Linux 教學

Linux 開機自動以普通用戶身分執行腳本:rc.local vs init.d 服務兩種做法

環境:Fedora 7,root 管理員,普通用戶 test1。目標:開機自動以 test1 身分執行 /home/test1/test.py(每次執行向 test.log 追加時間戳記)。

方案一:rc.local(最簡單)

編輯 /etc/rc.d/rc.local 末尾加入:

cd /home/test1
su test1 -c "python /home/test1/test.py"
  • cd 切換工作目錄,否則 Python 找不到 test.log 報權限錯誤。
  • su -c 將命令作為參數傳遞,避免開啟子 Shell 導致後續指令卡住。

方案二:init.d 服務腳本(功能較完整)

建立 /etc/rc.d/init.d/mystart:

#!/bin/bash
# chkconfig: 2345 80 05
# description: mystart service
RETVAL=0
start() {
    echo -n "mystart service ..."
    cd /home/test1
    su test1 -c "python /home/test1/test.py"
}
stop() {
    echo "mystart service is stopped..."
}
case $1 in
    start) start ;;
    stop) stop ;;
esac
exit $RETVAL

啟用步驟:

  1. chmod +x /etc/rc.d/init.d/mystart
  2. chkconfig --add mystart
  3. chkconfig --list mystart 確認

避坑指南

錯誤寫法:

su test1
cd /home/test1
python test.py
exit

原因:su test1 開啟子 Shell,後續指令需等子 Shell 結束才執行,而 Python 長期運行導致啟動流程卡死。正確做法皆為 su user -c "command" 單行傳遞。

copyright © 萬盛學電腦網 all rights reserved