概述
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.logexit 0
注意 :脚本或者开机执行的命令要在exit0之前。
- 在
/etc/systemd/system目录下创建rc-local.service服务的软链接。ln -s /lib/systemd/system/rc-local.service /etc/systemd/system/
- 或者执行以下命令,设置开机自启动该服务。
systemctl enable rc-local.service
没有帐号? 立即注册