最近為了讓宿舍電腦可以自動啟動OpenVPN,在網路上找了一下有關開機後自動執行程式的方式,在這裡整理一下。
A: 修改 /etc/rc.local
這方式算是最常見的做法。在一般的 Linux 來說,/etc/rc.local 就是開機自啟動的腳本。方法只要把執行的指令/腳本加入至rc.local即可。
~$ cat /etc/rc.local
#!/bin/sh -e
# rc.local
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
# In order to enable or disable this script just change the execution
# bits.
# By default this script does nothing.
# 輸入需要開機執行的程式/腳本
/home/mountain/run.sh &
exit 0
B: 新增腳本至/etc/init.d/
另一種常見的方法是在/etc/init.d 新增腳本,這方法可以把執行動作以不同指令進行分類,/etc/init.d/command 選項可以有如下幾種:
- start
- stop
- reload
- restart
- fore-reload
根據使用者需求,腳本可以按不同事件設定每一個command 動作。以下為新增腳本的方法。
-
- 新增腳本至/etc/init.d (NameOfYourScript為你腳本名字,請記得修改)
sudo nano /etc/init.d/NameOfYourScript
-
- 修改腳本內容,以下為一範例
#! /bin/sh
# /etc/init.d/noip
### BEGIN INIT INFO
# Provides: noip
# Required-Start: $remote_fs $syslog
# Required-Stop: $remote_fs $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Simple script to start a program at boot
# Description: A simple script from www.stuffaboutcode.comwhich will start / stop a program a boot / shutdown.
### END INIT INFO
# If you want a command to always run, put it here
# Carry out specific functions when asked to by the system
case "$1" in
start)
echo "Starting noip"
# run application you want to start
/usr/local/bin/noip2
;;
stop)
echo "Stopping noip"
# kill application you want to stop
killall noip2
;;
*)
echo "Usage: /etc/init.d/noip {start|stop}"
exit 1
;;
esac
exit 0
-
- 更新腳本權限,使得腳本可被執行
sudo chmod 755 /etc/init.d/NameOfYourScript
-
- 把腳本加入開機程序,讓腳本在開機時自動執行
sudo update-rc.d NameOfYourScript defaults
Reference:
- 理解Linux系統/etc/init.d目錄和/etc/rc.local腳本
https://hk.saowen.com/a/83ae554836e53662f112a38c2cdf7ad4935bca8b1077417754c192b695bfc5c2 - Raspberry Pi – run program at start up
https://www.stuffaboutcode.com/2012/06/raspberry-pi-run-program-at-start-up.html