晋级版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 & #每天重启
#!/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
#!/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)