美文网首页LinuxLinuxLinux.命令
如何让linux机器开机自动运行shell脚本

如何让linux机器开机自动运行shell脚本

作者: 狄仁杰666 | 来源:发表于2021-06-01 23:19 被阅读0次

前言

来啦老铁!

今天咱们一起来学个小知识点:

  • 如何让linux机器开机自动运行shell脚本;

背景是:有时候我们会遇到一些web服务部署在linux机器,而linux机器由于系统升级、人为重启等原因,会导致咱们的服务停掉,体验非常差,此类情况下需要一个开启自启动的办法;

参考文献:

整体步骤

  1. 确定服务启动命令,编写shell脚本;
  2. 推送shell脚本至linux机器;
  3. 拷贝shell脚本至启动目录下并设置文件访问权限;
  4. 更新系统启动脚本;
  5. 检查启动项状态;
  6. 再多走一步;

1. 确定服务启动命令,编写shell脚本;

比如咱们有个message-tool项目,其启动命令为:

nohup python3 main.py >server.log 2>&1 &

另外一个项目为ssim-service项目,其启动方式为:

  • 进入根目录下的backend文件夹,执行以下命令
nohup python3 main.py >server.log 2>&1 &
  • 进入根目录下的frontend文件夹,执行以下命令:
export HOST=0.0.0.0 && nohup yarn start >/dev/null 2>&1 &

那么,咱们可以在本地电脑先建一个start.sh脚本文件,并在该文件中写入以下脚本:

#!/bin/sh

# 启动消息工具
cd message-tool
nohup python3 main.py >server.log 2>&1 &

# 启动ssim工具
cd ..
cd ssim-service
cd backend
nohup python3 main.py >server.log 2>&1 &
cd ..
cd frontend
export HOST=0.0.0.0 && nohup yarn start >/dev/null 2>&1 &

exit 0

本地编写完保存后,咱们可以将该文件拷贝到与messag-tool、ssim-service项目同级的文件夹下(如果不同级,则需要修改shell脚本中的cd路径);

2. 推送shell脚本至linux机器;

由于我是mac,推送文件到linux的一种简单方式为:

scp start.sh diren@xxx.x.x.xxx:/home/diren
#格式为:scp 本地路径  Linux登录用户名@Linux ip地址:+Linu路径

然后输入linux机器的访问密码即可推送文件到我们指定的目录:/home/diren

3. 拷贝shell脚本至启动目录下并设置文件访问权限;

  • 拷贝文件:
sudo mv start.sh /etc/init.d/
  • 然后cd到/etc/init.d/目录:
cd /etc/init.d/
  • 设置start.sh文件的访问权限:
sudo chmod 755 start.sh

4. 更新系统启动脚本;

cd /etc/init.d/  
sudo update-rc.d start.sh defaults 90 

命令中的90为设置的启动序号,越大代表执行越晚;

5. 检查启动项状态;

以上步骤设置完成后,应该就能达到开机自启动的效果了,不过我没有条件重启机器,因此多走一步:

  • 检查服务状态:
sudo systemctl list-unit-files
服务状态

一个generated让我不知所以呀,enabled应该才是我们想要的,百度后有:

  • 另一个方式查看状态:
sudo systemctl status start.service
inactive
  • 使用命令启动服务:
systemctl start start.service
  • 再次检查服务状态:
active

这下才让我比较放心,虽然我没有重启机器验证,但也比较有信心啦!

6. 再多走一步;

  • 移除开机自启动脚本
sudo update-rc.d -f start.sh remove
  • 停止已经开启的服务:
sudo systemctl stop start.service
  • 重启服务:
sudo systemctl restart start.service
  • 禁用开机启动:
sudo systemctl disable start.service

如果本文对您有帮助,麻烦动动手指点点赞?

谢谢!

相关文章

网友评论

    本文标题:如何让linux机器开机自动运行shell脚本

    本文链接:https://www.haomeiwen.com/subject/msggsltx.html