鏡像下載、域名解析、時間同步請點擊 阿里巴巴開源鏡像站
一、概述
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 ‘ 加入鏡像站官方用戶交流群。”