[513]linux设置开机自启动

本文详细介绍在Linux环境下如何设置脚本自启动,包括编辑rc.local,使用systemd服务,以及在init.d目录下添加脚本的方法。同时,文章也介绍了如何在关机时执行特定命令。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

自启动方法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.youkuaiyun.com/hualinger/article/details/125321966

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

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

周小董

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值