rc.local不会开机自启问题

503 阅读1分钟

有时我们需要在开机启动的时候运行一些自己写的脚本,把运行脚本的命令加入到rc.local中是最简单的方法,但是这个文件可能不运行。

可能原因:

一、 rc.local没有执行权限

增加权限:

sudo chmod +x /etc/rc.local

二、rc-local.service服务没有启动

rc-local.service服务是与rc.local的启动相关联的,该服务启动了rc.local才会在开机的时候运行。

检测服务是否启动:

systemctl status rc-local.service

如果active的状态是failed,表示服务没有启动。

1. 启动服务:

systemctl start rc-local.service

2. 设置开机自启:

systemctl enable rc-local.service

如果执行 systemctl enable rc-local.service 报错如下:

The unit files have no installation config (WantedBy, RequiredBy, Also, Alias settings in the [Install] section, and DefaultInstance for template units).

解决办法:

rc-local.service添加Install字段。

[Install]
WantedBy=multi-user.target

结果:

cat /lib/systemd/system/rc-local.service  
[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

注意:开机自启的脚本需要写入该文件中提及的 rc.local 中 如此处为 /etc/rc.local,有的是 /etc/rc.d/rc.local

重新enable

systemctl enable rc-local.service

创建/etc/rc.local,并赋予执行权限

验证如下:

cat /etc/rc.local
#!/bin/sh
echo "ok" >> ~/rc.local.ok
exit 0

再次检测服务是否启动,若启动成功,rc.local在开机的时候就可以自动运行了。

三、如果服务无法启动,修改rc.local的第一行:

#!/bin/bash

参考

rc.local不会开机自启问题_、-若木的博客-CSDN博客
解决办法:The unit files have no [Install] section. - 天行常 (const.net.cn)