Java OpenResty Spring Spring Boot MySQL Redis MongoDB PostgreSQL Linux Android Nginx 面试 小程序 Arthas JVM AQS juc Kubernetes Docker 诊断工具


Linux Shell 脚本监控进程状态

Linux Shell cron 大约 1411 字

背景

此处以监测Elasticsearch进程是否存活为例。

cron 定时任务

  • 优点:系统进程,不易被回收
  • 缺点:频率最低为一分钟执行一次

脚本

注意:监控其他服务只需要替换java为对应的进程即可,如替换为进程中包含mongod-shardsvr1.conf字符的进程。

#!/bin/bash
count=`ps aux | grep 'java' | grep -v 'grep' -c`
if [ $count -eq 0 ]; then
        now=`date +%F\ %T`
        echo "[$now] Elasticseach is offline, try to restart..." >> /elasticsearch/check_es.log
        /elasticsearch/elasticsearch-7.0.0/bin/elasticsearch -d
else
        now=`date +%F\ %T`
        echo "[$now] Elasticsearch is online, everything seems to be OK..." >> /elasticsearch/check_es.log
fi

cron 配置

注意:一些进程可能需要root用户才能启动,所以可能cron也需切换到root用户才能生效。

查看现有定时任务

crontab -l

编辑定时任务

crontab -e

设置每分钟执行一次脚本

* * * * * /bin/bash /elasticsearch/check_es.sh

查看定时任务执行日志

tail -f /var/log/cron

查看脚本执行日志(自定义输出的日志)

tail -f /elasticsearch/check_es.log

后台 shell 进程

  • 优点:频率可最低设置为一秒一次
  • 缺点:作为用户级别的后台进程,可能被回收

脚本

while true;
do
    count=`ps aux | grep -v 'grep' | grep -c 'java'`
    if [ $count -eq 0 ]; then
            now=`date +%F\ %T`
            echo "[$now] Elasticseach is offline, try to restart..." >> /elasticsearch/check_es.log
            /elasticsearch/elasticsearch-7.0.0/bin/elasticsearch -d
    else
            now=`date +%F\ %T`
            echo "[$now] Elasticsearch is online, everything seems to be OK..." >> /elasticsearch/check_es.log
    fi
    sleep 1
done

执行 shell

nohup ./monitor.sh >/dev/null 2>&1 & 
阅读 4793 · 发布于 2019-08-10

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb

扫描下方二维码关注公众号和小程序↓↓↓

扫描二维码关注我
昵称:
随便看看 换一批