python2-监控多目录error错误日志,实时发送到指定钉钉群(版本3)

晋级版python3的:https://blog.csdn.net/liyyzz33/article/details/97789920
这个比较老了也可参考

通过自动任务执行监控sh文件,通过python常链接日志文件发送到钉钉

自动任务

1 0 * * * /root/alarmd.sh stop > /dev/null 2>&1 & #每分钟检查一次
*/1 * * * * /root/alarmd.sh start > /dev/null 2>&1 & #每天重启

alarmd.sh

#!/bin/bash

comm=$1
serverip=`192.168.1.123`
date=`date +%Y%m%d`

pro1='/data/logs/dalu/'
pro2='/data/logs/dalu2/'
pro3='/data/logs/dalu2/'
pro4='/data/logs/dalu3/'
pro5='/data/logs/dalu4/'

echo $comm

function start () {

	
Pystatus=`ps -ef | grep $1 | grep -v grep |grep python | wc -l`

if [ $Pystatus -eq 0 ];
	
	then
	
	echo "`date "+%Y-%m-%d %H:%M:%S"`:$1 is not running" >> /data/logs/python.log    
	
	nohup python /root/alarm.py $1 $serverip &
	
	echo "`date "+%Y-%m-%d %H:%M:%S"`:$1 is starting" >> /data/logs/python.log

	sleep 5
		
	CurrentPystatus=`ps -ef | grep $1 | grep -v grep |grep python | wc -l`
	
	if [ $CurrentPystatus -ne 0 ];
	then
	echo "`date "+%Y-%m-%d %H:%M:%S"`:$1 is running" >> /data/logs/python.log	
	fi
fi
}


if [ "$comm" = "start" ];then

	cd /data/logs

	for dirpath in $pro{1..4}

	do	
		for error in `find $dirpath -maxdepth 1 -name "*$date.log"`
		do
			echo $error
			start $error 
		done
		
	done
	
elif [ "$comm" = "stop" ];then

ps -ef|grep /root/alarm.py |grep -v grep|cut -c 9-15|xargs kill -9

else
	echo "输入有误,请带参数stop or start!"
	
fi

alarm.py

#!/usr/bin/python
# -*- coding: utf-8 -*

import json
import sys,os
import time
import urllib2


DING_MSG_ID_www = "ccaeb3ad08e0b****************************************"  # PHP_www_error
DING_MSG_ID_dalu = "ccaeb3ad08e0b****************************************"  # 上传图片失败告警内部  业主APP



filepath =sys.argv[1]
serverip =sys.argv[2]


errmsg = ""



def dingtalk_post( tokenid ,errmsg ):

    url = "https://oapi.dingtalk.com/robot/send?access_token=%s" % tokenid
    values = {'msgtype': 'text'}
    content = {}
    content['content'] = serverip + errmsg
    values['text'] = content
    headers = {'Content-Type':'application/json;charset=UTF-8'}
    jdata = json.dumps(values)
    print jdata
    req = urllib2.Request(url, jdata , headers)
    response = urllib2.urlopen(req)
    data = json.loads(response.read())
    errcode = data['errcode']
    print errcode
    return errcode

file = open(filepath)
file.seek(0, os.SEEK_END)
while 1:
        where = file.tell()
        line = file.readline()
        if not line:
                time.sleep(1)
                file.seek(where)
        else:
            if  'dalu3' in filepath :
                    dingtalk_post(DING_MSG_ID_www ,line)
            elif  'dalu2' in filepath :
                   dingtalk_post(DING_MSG_ID_www ,line)
            else:
                  dingtalk_post(DING_MSG_ID_www , line)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值