ubuntu 18.04 设置开机自启

ubuntu 18.04 设置开机自启

背景

为了添加一些自定义的服务,例如autossh。

原文(有删改):https://zhuanlan.zhihu.com/p/98804785

介绍

ubuntu 18.04 使用 systemd 管理系统(16.04 initd),systemd 默认读取 /etc/systemd/system目录下的配置文件,并链接到 /lib/systemd/system/目录下的脚本文件;

做法

修改启动服务

rc.local.service是我们所需要的自启动脚本

sudo vim /lib/systemd/system/rc.local.service

在末尾添加 [Install] 字段,如下:

#  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

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

创建 rc.local脚本

创建 rc.local脚本(ubuntu 18.04 下没有这个脚本,需自行创建),并添加执行权限

sudo touch /etc/rc.local; sudo chmod a+x /etc/rc.local

创建软链接

/etc/systemd/system目录下创建软链接

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

编写启动脚本

把需要的内容写入:sudo vim /etc/rc.local

例如,

# 修改 rc.local 脚本,添加下面内容
echo "test" > /usr/local/text.log

测试

重启:reboot

重启后,查看 /usr/local/text.log

sudo cat /usr/local/text.log
posted @ 2021-06-21 15:27  schips  阅读(691)  评论(0编辑  收藏  举报