Linux使用脚本监控某个服务状态,并在服务启动失败时自动执行重启【测试成功】

艺帆风顺 发布于 2025-04-03 29 次阅读


一、需求背景

    某个服务采用定时重启,发现在一次重启后失败了,但是没有继续重启的操作,导致业务系统中断,加入监控服务状态并执行自动重启机制。

二、配置脚本

    编写shell脚本:

    #!/bin/bash
    # 设置日志文件路径log_file="$(dirname "$0")/YLMS_restart.log"
    while true; do # 获取当前时间 current_time=$(date +"%Y-%m-%d %H:%M:%S")
    # 获取YLMS服务的状态 service_status=$(systemctl status YLMS | grep "Active:")
    # 检查服务状态 if [[ $service_status == *"failed"* ]]; then echo "$current_time - 服务状态为failed,执行重启操作..." systemctl restart YLMS echo "$current_time - 服务已重启" >> "$log_file" elif [[ $service_status == *"active (running)"* ]]; then echo "$current_time - 服务正常,无需重启" echo "$current_time - 服务正常,无需重启" >> "$log_file" break # 服务正常时退出循环 else echo "$current_time - 无法确定服务状态" echo "$current_time - 无法确定服务状态" >> "$log_file" fi
    sleep 60done

    三、配置定时任务

        crontab -e

    */2 * * * * /temp/sh/3.sh

    四、查看效果