java 监控linux进程_Linux Shell脚本监控进程状态

背景

此处以监测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 &

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值