ubuntu 18.04 如何设置开机自动启动脚本

Ubuntu 18.04及更高版本使用systemd代替了传统的rc.local,因此不能直接在rc.local中添加脚本实现开机启动。本文详细介绍了如何通过systemd配置开机自动运行自定义脚本,包括创建service文件、设置开机启动服务等步骤,确保脚本在多用户模式下网络启动后运行。
摘要由CSDN通过智能技术生成

本文来自于【阿里云官方镜像站:https://developer.aliyun.com/mirror/?utm_content=g_1000307095 】

原文链接:https://developer.aliyun.com/article/761346?spm=a2c6h.12873581.0.0.484f7e46SbqQDx

镜像下载、域名解析、时间同步请点击 阿里巴巴开源镜像站

一、概述

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=0RemainAfterExit=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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值