Ubuntu 18.04 STL下正确的开机自启动配置方案

    科技2022-07-29  130

    Ubuntu 18.04 STL下正确的开机自启动配置方案

    看了几个网上的教程,或多或少都有问题,实在是火大,遂决定整理一波。有问题的文章如下:

    https://zhuanlan.zhihu.com/p/98804785

    http://www.r9it.com/20180613/ubuntu-18.04-auto-start.html

    问题一堆,常见的如.和-不区分、步骤不全等。

    正确的操作方式

    1. 基于systemd的系统管理

    ubuntu 16.10之后已经不用initd(就是PID序号为1的那个进程)管理系统了,而systemd默认读取的是/lib/systemd/system/目录下的文件。所以我们配置一个新服务如下:

    cd /lib/systemd/system gedit rc-local.service 如果rc-local.service不小心误删了,手动创建一下:touch 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 # 添加的是以下内容,本行注释请注意移除。 [Install] WantedBy=multi-user.target Alias=rc-local.service

    2.开机启动项

    注意到ExecStart=/etc/rc.local start行告诉我们开机自启的逻辑,所以需要在/etc/rc.local文件中进行配置你要的开机启动项(如果该文件不存在请创建):

    #!/bin/sh -e # # rc.local # 以上三行以#开头的请不要移除,下面几行中文注释请移除 # 你的开机命令写在下方(exit 0的上方,注意空一行),例如我写两个autossh的命令 # 注意移除中文的注释 autossh -M 55555 -fCNR 2061:localhost:22 example@111.11.111.11 exit 0

    接着给该文件增加执行权限:

    chmod a+x /etc/rc.local

    3.软连接

    在/etc/systemd/system/创建一个到/lib/systemd/system/的软连接:

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

    查看映射是否正确建立:

    ls -al /etc/systemd/system/rc-local.service

    正常的话,显示如下:

    lrwxrwxrwx 1 root root 36 10月 4 22:32 /etc/systemd/system/rc-local.service -> /lib/systemd/system/rc-local.service

    4.启动服务

    systemctl enable rc-local.service 查看服务是否顺利启动:systemctl status rc-local.service,正常应当显示为:active(running),否则重启电脑,检查以上各个步骤是否正确操作。
    Processed: 0.012, SQL: 8