Debian 开机自动执行脚本任务

前言

由于某些软件并没有增加开启启动的服务,很多时候需要手工添加,一般我们都是推荐添加命令到 /etc/rc.local 文件,但是 Debian 9 以后系统默认不带 /etc/rc.local 文件,而 rc.local 服务却仍自带,默认情况下这个服务是处于关闭的状态,我们可以通过添加 rc.local 文件并开启来解决开机自动执行的问题。

操作流程

添加 rc.local.service 文件(不自带可选)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
cat > /etc/systemd/system/rc.local.service <<EOF
[Unit]
Description=/etc/rc.local
ConditionPathExists=/etc/rc.local

[Service]
Type=forking
ExecStart=/etc/rc.local start
TimeoutSec=0
StandardOutput=tty
RemainAfterExit=yes
SysVStartPriority=99

[Install]
WantedBy=multi-user.target
EOF

添加 rc.local 文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
cat <<EOF >/etc/rc.local
#!/bin/sh -e
#
# 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.

exit 0
EOF

添加权限并设置开机自启

1
2
3
chmod +x /etc/rc.local
systemctl enable rc.local
systemctl start rc.local.service

查看状态

1
systemctl status rc-local

添加自启任务

把需要开机启动的命令添加到 /etc/rc.local 文件的 exit 0 前面即可,并尝试重启验证是否生效。