2020年11月3日 星期二

Ubuntu 18.04 開機自動執行程式

 之前提到過

Ubuntu 16.04 開機自動執行程式,

不過到了 Ubuntu 18.04 就會發現該方法已經不適用,

這是因為 Ubuntu 18.04 改用 systemd ,

今天就來教大家在

Ubuntu 18.04 開機自動執行程式

systemd 預設會讀取 /etc/systemd/system,

此資料夾的服務許多都 link 到 /lib/systemd/system中的文件,

例如 SSH 服務:

sshd.service -> /lib/systemd/system/ssh.service

簡單的說就是將要自動執行的加入到這些服務中即可,

首先要新增一個服務,

sudo vi /etc/systemd/system/rc-local.service




並將以下內容加入:

[Unit]
Description=/etc/rc.local Compatibility
ConditionPathExists=/etc/rc.local
 
[Service]
Type=forking
ExecStart=/etc/rc.local start
TimeoutSec=0
StandardOutput=tty
RemainAfterExit=yes
SysVStartPriority=99
 
[Install]
WantedBy=multi-user.target

這三個區段在系統分別代表:

Unit,可在此定義順序,依賴關係
Service,可在此定義執行指令,執行類型
Install,可在此設定執行的層級

此處的 multi-user.target
指的是 文字模式,也就是 console 模式,

接著建立要執行的命令:

sudo vi /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.
echo "auto run success" > /usr/local/test.log
在此插入要執行的程式
exit 0

存檔後離開並設定為可執行:

chmod 755 /etc/rc.local

最後將服務啟用:

sudo systemctl enable rc-local

這就是今天的

Ubuntu 18.04 開機自動執行程式

在不重新開機的情況下測試的話,

可使用

sudo systemctl start rc-local.service
sudo systemctl status rc-local.service

來啟動服務並檢查服務執行的情形,



由於有新增 log ,

也可透過檢查

 /usr/local/test.log 的內容  "auto run success" 是否存在,

確定程式是否已執行。

沒有留言: