Ubuntu18.04 设置开机启动脚本

转自:https://zhuanlan.zhihu.com/p/134104040

前言:ubuntu18.04 不再使用initd管理系统,改用systemd,本文教大家如何像以前一样使用rc.local配置开机启动脚本

原理:系统的systemd会自动读取/etc/systemd/system/下的配置文件,该目录下的文件会链接到/lib/systemd/system/下,我们系统会自带rc-local.service/lib/systemd/system/

  1. 修改/lib/systemd/system/rc-local.service,在后面增加install区块
sudo vim /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] 段: 定义如何安装这个配置文件,即怎样做到开机启动

可以看出,/etc/rc.local 的启动顺序是在网络后面,但是显然它少了 Install 段,也就没有定义如何做到开机启动,所以显然这样配置是无效的。 因此我们就需要在后面帮他加上 [Install] 段:

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

2. 将rc-local.service文件软连接到/etc/systemd/system/

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

3. 创建rc.local文件(ubuntu18.04默认无此文件)

sudo vim /etc/rc.local
# 编辑您需要开机启动的命令
# 如
sudo echo '开机启动测试文案' > /var/test.log

4. 给rc.local加上可执行权限

sudo chmod +x /etc/rc.local 

5. 完成,测试一遍

# 重启系统
reboot

# 重启后查看刚刚的测试命令是否生效
sudo cat /var/test.log
开机启动测试文案

# 开机启动设置成功!

6. 配置完成!

You May Also Like

About the Author: ice.zhai

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注