#!/usr/bin/env python3
# -*- conding: utf-8 -*-
import os
import time
import requests
import json
import psutil
#CPU,MEM,NET,IO,DISK,SERVER,PROCESS
url = '输入你的机器人webhook'
time_now = time.strftime('%Y-%M-%d %H:%M:$S',time.localtime(time.time()))
monitor_name = {'httpd','sshd'}
#预监控服务
monitor_map = {
'httpd':'systemctl start httpd'
}
while True:
proc_dict = {}
#PID:进程名
proc_name = set()
#进程名集合
for p in psutil.process_iter(attrs=['pid','name']):
#当前操作系统下所有进程名及进程ID
proc_dict[p.info['pid']] = p.info['name']
proc_name.add(p.info['name'])
proc_stop = monitor_name - proc_name
#未开启的进程
if proc_stop:
for p in proc_stop:
p_status = '停止!'
p_name = p
data = {
"msgtype":"markdown",
"markdown":{
"title":"监控讯息",
"text":"#### %s\n" % time_now +
"> #### 服务名:%s \n\n" % p_name +
"> #### 状态: %s \n" % p_status +
"> #### 正在尝试启动"
}
}
'''
"at":{
"atMobiles":[
"152xxxxxxxx",
],
"isAtAll":True
}
'''
headers = {'Content-Type':'application/json;charset=utf-8'}
send_data = json.dumps(data).encode('utf-8')
requests.post(url=url,data=send_data,headers=headers)
#post提交数据
os.system(monitor_map[p])
proc_name = set()
for p1 in psutil.process_iter(attrs=['pid','name']):
proc_name.add(p1.info['name'])
if p in proc_name:
p_status = '启动!'
p_name = p
data = {
"msgtype":"markdown",
"markdown":{
"title":"监控讯息",
"text":"#### %s\n" % time_now +
"> #### 服务名:%s \n\n" % p_name +
"> #### 状态: %s \n" % p_status +
"> #### 重启成功!"
}
}
headers = {'Content-Type':'application/json;charset=utf-8'}
send_data = json.dumps(data).encode('utf-8')
requests.post(url=url,data=send_data,headers=headers)
else:
p_status = '停止!'
p_name = p
data = {
"msgtype":"markdown",
"markdown":{
"title":"监控讯息",
"text":"#### %s\n" % time_now +
"> #### 服务名:%s \n\n" % p_name +
"> #### 状态: %s \n" % p_status +
"> #### 启动失败!"
}
}
headers = {'Content-Type':'application/json;charset=utf-8'}
send_data = json.dumps(data).encode('utf-8')
requests.post(url=url,data=send_data,headers=headers)
else:
for p in monitor_name:
p_status = '运行中!'
p_name = p
data = {
"msgtype":"markdown",
"markdown":{
"title":"监控讯息",
"text":"#### %s\n" % time_now +
"> #### 服务名:%s \n\n" % p_name +
"> #### 状态: %s \n" % p_status +
"> #### 进程正常!"
}
}
headers = {'Content-Type':'application/json;charset=utf-8'}
send_data = json.dumps(data).encode('utf-8')
requests.post(url=url,data=send_data,headers=headers)
time.sleep(2)
钉钉监控服务器进程
最新推荐文章于 2023-10-31 14:08:55 发布