Ubuntu 18.04設置開機自動啓動

Ubuntu 16.10開始不再使用initd管理系統,改用systemd,包括用systemctl命令來替換了service和chkconfig的功能。比如以前啓動mysql服務用sudo service mysql start,現在用sudo systemctl start mysqld.service。systemd 默認讀取 /etc/systemd/system 下的配置文件,該目錄下的文件會鏈接/lib/systemd/system/下的文件。

執行命令ls /lib/systemd/system可以看到很多啓動腳本,其中就有我們需要的rc.local.service,打開腳本內容如下

#  SPDX-License-Identifier: LGPL-2.1+
#
#  This file is part of systemd.
#
#  systemd is free software; you can redistribute it and/or modify it
#  under the terms of the GNU Lesser General Public License as published by
#  the Free Software Foundation; either version 2.1 of the License, or
#  (at your option) any later version.

# This unit gets pulled automatically into multi-user.target by
# systemd-rc-local-generator if /etc/rc.local is executable.
[Unit]
Description=/etc/rc.local Compatibility
Documentation=man:systemd-rc-local-generator(8)
ConditionFileIsExecutable=/etc/rc.local
After=network.target

[Service]
Type=forking
ExecStart=/etc/rc.local start
TimeoutSec=0
RemainAfterExit=yes
GuessMainPID=no

一般啓動文件需要三個組成部分

[Unit]段: 啓動順序與依賴關係

[Service] 段: 啓動行爲,如何啓動,啓動類型

[Install] 段: 定義如何安裝這個配置文件,即怎樣做到開機啓動

上面少了[Install] 段,把下面Install段添上去

[Install]  
WantedBy=multi-user.target  
Alias=rc-local.service

Ubuntu-18.04 默認是沒有 /etc/rc.local 這個文件的,需要自己創建

sudo touch /etc/rc.local

前面我們說 systemd 默認讀取 /etc/systemd/system 下的配置文件, 所以還需要在 /etc/systemd/system 目錄下創建軟鏈接

sudo ln -s /lib/systemd/system/rc.local.service /etc/systemd/system/

然後把你需要啓動腳本寫入 /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.

sudo echo "看到這行字,說明添加自啓動腳本成功" > /usr/local/text.log
exit 0

給rc.local加可執行權限

sudo chmod +x /etc/rc.local

啓動服務並檢查服務狀態

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

重啓後查看是否有text.log生成,以及寫入內容是否爲this just a test

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章