天天看點

ubuntu 18.04 如何設定開機自動啟動腳本

ubuntu 18.04 如何設定開機自動啟動腳本

鏡像下載下傳、域名解析、時間同步請點選

阿裡巴巴開源鏡像站

一、概述

Ubuntu 18.04版本預設沒有

/etc/rc.local

檔案,已經無法通過在該檔案中添加腳本來保證開機自動執行。那如何保證自己寫的腳本可以開機自動運作呢?從Ubuntu 16.10版本開始不再使用initd管理系統,改用systemd管理系統,而通過systemd管理系統可以實作開機運作自己的腳本 ,本文講解如何通過systemd來實作開機自動運作腳本。

二、配置方法

注意:
  • 如果您對執行個體或資料有修改、變更等風險操作,務必注意執行個體的容災、容錯能力,確定資料安全。
  • 如果您對執行個體(包括但不限于ECS、RDS)等進行配置與資料修改,建議提前建立快照或開啟RDS日志備份等功能。
  • 如果您在阿裡雲平台授權或者送出過登入賬号、密碼等安全資訊,建議您及時修改。

systemd管理系統預設讀取

/etc/systemd/system

的配置檔案,該目錄下的檔案會連結

/lib/systemd/system/

的檔案。執行

ls /lib/systemd/system

指令可以看到有很多啟動腳本,其中就需要打開

rc.local.service

檔案并檢視内容。

#  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
ConditionFileIsExecutable=/etc/rc.local
After=network.target
[Service]
Type=forking
ExecStart=/etc/rc.local start
TimeoutSec=0
RemainAfterExit=yes           

正常的啟動檔案主要分成以下三部分:

  • [Unit]段: 啟動順序與依賴關系。
  • [Service]段: 啟動行為,如何啟動,啟動類型。
  • [Install]段: 定義如何安裝這個配置檔案,即怎樣做到開機啟動。

可以看出

/etc/rc.local

檔案的啟動順序是在網絡後面,但是顯然它少了[Install]段,也就沒有定義如何做到開機啟動,是以這樣配置是無效的。是以我們就需要在後面幫他加上[Install]段:

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

因為Ubuntu18.04預設沒有

/etc/rc.local

這個檔案,是以需要建立。然後您需要将開機啟動腳本寫入

/etc/rc.local

檔案,最後測試開機啟動後在

root Home

目錄下生成以下文本檔案。

#!/bin/bash
# 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 Test file > ~root/text.log
exit 0           
注意 :腳本或者開機執行的指令要在exit0之前。

1、在

/etc/systemd/system

目錄下建立

rc.local.service

服務的軟連結。

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

2、或者執行以下指令,設定開機自啟動該服務。

systemctl enable rc-local.service           
提供全面,高效和穩定的鏡像下載下傳服務。釘釘搜尋 ' 21746399 ‘ 加入鏡像站官方使用者交流群。”