前言
工作上的需求,需要写一个告警中转程序,写完后又怕挂掉没人知道,就写了这个简单进程检测脚本,如果有进程不存在则发出钉钉告警。
1. Linux kill -0
kill 命令如果参数是 0,不会发送任何的信号,但是仍会执行错误检查,可以用他来检测某个进程ID或进程组 ID 是否存在。
2. 脚本展示
使用 kill -0 来检测进程是否存在,使用 crontab
每小时执行一次。
# -*- coding: utf-8 -*-
import sys
import os
import json
import requests
# crontab -l
# 0 */1 * * * python3 /opt/monitor_process.py 进程号码
def send_massage(pid):
content = '【进程探活告警】您的 {0} 进程检测异常,请登陆环境查看。'.format(str(pid))
# 这里写你的钉钉群 webhook
webhook = ''
header = {
"Content-Type": "application/json",
"Charset": "UTF-8"
}
message = {
"msgtype": "text",
"text": {
"content": content
},
# "at": {
# "isAtAll": True
# }
}
message_json = json.dumps(message)
info = requests.post(url=webhook, data=message_json, headers=header)
# print(info)
def monitor_process(pid):
try:
os.kill(pid, 0)
# print(process_id)
except ProcessLookupError:
# 表示进程不存在
# print('ProcessLookupError')
send_massage(pid)
process_id = int(sys.argv[1])
# 运行函数
monitor_process(process_id)