在CentOS8 之前通过把需要开机执行的命令写入到/etc/rc.local 就解决了开机启动问题,但是从CentOS8开始写入到rc.local 将无法自动启动,需要设置 rc.local这个服务自启解决开机/etc/rc.local 中脚本不执行问题。

Centos8 设置开机自启动脚本_自动启动

[root@hostname]# more /etc/rc.local  
#!/bin/bash
THIS FILE IS ADDED FOR COMPATIBILITY PURPOSES
It is highly advisable to create own systemd services or udev rules
to run scripts during boot instead of using this file.

看一下系统默认/etc/rc.local的情况

[root@hostname]# ll /etc/rc.local  
lrwxrwxrwx 1 root root 13 Jul 1 2019 /etc/rc.local -> rc.d/rc.local
[root@hostname]# ll /etc/rc.d/rc.local
-rw-r--r--. 1 root root 474 Jul 1 2019 /etc/rc.d/rc.local

说明:可以看到当前的/etc/rc.local是 /etc/rc.d/rc.local文件的一个符号链接。

配置rc-local服务

我们在这里配置一个例子:开机后自动在/tmp 创建一个txt 文档

1、编辑/etc/rc.local文件

[root@hostname]# vi /etc/rc.local

增加一行:

touch /tmp/123.txt

2、加入可执行属性

[root@hostname]# chmod +x /etc/rc.d/rc.local   #必不可少,不然后面rc-local 无法启动

[root@hostname]# ll /etc/rc.d/rc.local
-rwxr-xr-x 1 root root 530 Mar 11 14:44 /etc/rc.d/rc.local

3、配置rc.local服务

[root@hostname]# vi /usr/lib/systemd/system/rc-local.service

内容如下:

[Unit]
Description=/etc/rc.d/rc.local Compatibility
Documentation=man:systemd-rc-local-generator(8)
ConditionFileIsExecutable=/etc/rc.d/rc.local
After=network.target

[Service]
Type=forking
ExecStart=/etc/rc.d/rc.local start
TimeoutSec=0
RemainAfterExit=yes
GuessMainPID=no

[Install]
WantedBy=multi-user.target

说明:最后的install一段不可少,如果当前的service文件中没有这段,需手动添加(默认有前两部分) 否则服务启动时会报错

4、启动rc-local服务

[root@hostname]# systemctl daemon-reload  
[root@hostname]# systemctl start rc-local

5、使开机能自动启动:

[root@hostname]# systememctl enable rc-local  
Created symlink /etc/systemd/system/multi-user.target.wants/rc-local.service /usr/lib/systemd/

system/rc-local.service.

测试

source /etc/rc.local 看下是否自动创建txt 文件 ,如创建成功说明脚本(这里只是写了一个简单的命令代替)自身不存在问题,删除这个txt 文件 并重启机器;机器启动后查看文件是否存在,如存在说明rc-local服务配置正常。