本文中的操作需要Root权限,或者需要有sudo权限的管理员账号。

在LinuxMint中,默认是没有启动rc.local的功能的,这样的设定给需要添加开机自启动的操作带来了一定的麻烦。因日常的使用和维护的过程中,有一些操作可能不是通过systemd来结果的,而是通过脚本的方式来启动和管理的。

下面的内容将演示怎么在LinuxMint系统下开启rc.local文件和它对应的服务。

查看/lib/systemd/system/rc-local.service文件,没有没有启动rc.local功能的情况下,文件的内容应该是这样的。

sean@sean-virtual-machine:~$ cat /lib/systemd/system/rc-local.service 
#  SPDX-License-Identifier: LGPL-2.1-or-later
#
#  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

使用nano命令编辑/lib/systemd/system/rc-local.service文件

sean@sean-virtual-machine:~$ sudo nano /lib/systemd/system/rc-local.service

在/lib/systemd/system/rc-local.service文件的末尾追加下面的内容,指定默认启动时激活的目标是多用户命令行环境

[Install]
WantedBy=multi-user.target 

保存后,配置rc-local开机自启动,同时创建/etc/rc.local文件,该文件默认是不存在的,

sean@sean-virtual-machine:~$ sudo systemctl enable rc-local
Created symlink /etc/systemd/system/multi-user.target.wants/rc-local.service → /lib/systemd/system/rc-local.service.
sean@sean-virtual-machine:~$ sudo nano /etc/rc.local

/etc/rc.local文件的格式如下:

#!/bin/bash -e

# 你想开机执行的命令

exit 0

编写完成后,给文件赋权。

sean@sean-virtual-machine:~$ sudo chmod 755 /etc/rc.local

截图的例子是在开机的时候,打印服务器的时间追加到/home/sean/logindate.txt文件中。

重启服务器测试其运行效果。