本文来自于【阿里云官方镜像站: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. Android(安卓)Studio启动DDMS
  2. Eclipse下Android-SDK-1.5模拟器启动设置
  3. android点滴(11) -- Android常用命令
  4. App 启动页出现短暂闪屏的解决方案
  5. Android(安卓)app开机启动
  6. android中启动服务
  7. android cmd
  8. Android(安卓)程序开机自启动
  9. Android(安卓)adb.exe程序启动不起来

随机推荐

  1. android视频处理相关资料
  2. Android(安卓)面试 指南:互联网大厂需要怎
  3. Android TextView 最全的XML属性
  4. Android发送SOAP数据给服务器调用webserv
  5. Android 开发入门-详解4种基本布局
  6. 《android开发应用实战详解》光盘源代码
  7. Ogre 1.9 RC1 发布了,有了官方的Android支
  8. android 一直在最前面的浮动窗口效果
  9. Android Camera使用小结
  10. app_gallery_best.xml 2