编辑/etc/rc.local文件

sudo vi /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

之后保存并退出

然后执行

sudo chmod 755 /etc/rc.local
sudo 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). This means they are not meant to be enabled using systemctl. 
Possible reasons for having this kind of units are: 
1) A unit may be statically enabled by being symlinked from another unit's .wants/ or .requires/ directory. 
2) A unit's purpose may be to act as a helper for some other unit which has a requirement dependency on it. 
3) A unit may be started when needed via activation (socket, path, timer, D-Bus, udev, scripted systemctl call, ...). 
4) In case of template units

就去设置rc-local.service

执行sudo vim /etc/systemd/system/rc-local.service

添加以下内容

[Unit]
 Description=/etc/rc.local Compatibility
 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

再次执行

sudo systemctl enable rc-local.service

注意:

注意你要开机执行的语句,如果包含路径,最好使用决定路径

另一个办法

还有一个/etc/init.d/中创建自己的开机运行脚本的方法,可以参考Ubuntu/Linux 开机运行指定的命令/自动运行命令

本文参考:

  1. Ubuntu下添加开机启动脚本
  2. Ubuntu /etc/rc.local 不存在
  3. Linux中没有rc.local文件的解决方法