当前位置: 首页 > 工具软件 > XLinux > 使用案例 >

[513]linux设置开机自启动

韦智刚
2023-12-01

自启动方法1

1、权限编辑/etc/rc.d/rc.local

cd /etc/rc.d/
vim rc.local

2、在末尾添加执行脚本命令

sh /home/test.sh

3、给脚本赋权限

chmod +x /etc/rc.d/rc.local
chmod +x /home/test.sh

自启动方法2

1、添加启动服务

cd /usr/lib/systemd/system

vim test-autorun.service

将以下内容写到service

[Unit]
Description=emqx for auto start
Wants=network-online.target

[Service]
User=root
Type=forking
ExecStart=/usr/bin/bash /home/test.sh start
ExecStop=/usr/bin/bash /root/test.sh stop

[Install]
WantedBy=multi-user.target

2、重新加载systemd配置

systemctl daemon-reload

3、添加开机自启动

systemctl enable test-autorun.service
  • 重启
$  sudo reboot
  • 查看服务状态
$  sudo systemctl status test-autorun.service

方法3:在/etc/rc.d/init.d目录下添加自启动脚本

linux在/etc/rc.d/init.d下有很多的文件,每个文件都是可以看到内容的,其实都是一些shell脚本或者可执行二进制文件。

Linux开机的时候,会加载运行/etc/init.d目录下的程序,因此我们可以把想要自动运行的脚本放到这个目录下即可。系统服务的启动就是通过这种方式实现的。

PS:添加完后务必设置文件的可执行权限 chmod +x filename

关机要执行的命令

如果你的系统使用systemd,你可以在/lib/systemd/system-shutdown/目录中添加一个脚本,systemd-halt.service会处理这个目录中的脚本。

示例(Ubuntu 16.04):

$ sudo vim /lib/systemd/system-shutdown/cleanup.service
[Unit]
Description=Run command at shutdown
# 假设要执行的命令依赖网络
Requires=network.target
DefaultDependencies=no
Before=shutdown.target reboot.target
 
[Service]
Type=oneshot
RemainAfterExit=true
ExecStart=/bin/true
ExecStop=<要执行的命令>(/bin/touch /home/snail/hello)
 
[Install]
WantedBy=multi-user.target

参考:
https://www.cnblogs.com/shih945/p/16561299.html
https://www.cnblogs.com/vofill/p/15752997.html
https://blog.csdn.net/hualinger/article/details/125321966

http://blog.topspeedsnail.com/archives/10203#more-10203

 类似资料: