[Python Study Notes]进程信息(丁丁软件监控进程,http-post)

'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
>>文件: 进程信息.py
>>作者: liu yang
>>邮箱: liuyang0001@outlook.com ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' #!/usr/bin/env python
# -*- coding: utf-8 -*- import sys,os
import psutil # http get/post
import requests
# 处理字符串
import json
# 获取系统时间
import time # 丁丁url
url = 'https://oapi.dingtalk.com/robot/send?access_token=3d94c740a27d5f70da6acf2a1c9383b338ad5c562fbaece8d38595c405e7e6a9'
# 转换成当前的时间戳
time_now = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
# 要监控的进程
monitor_name = {'ufw'}
# 要监控的进程,与shell语句对应,先定义为空
monitor_map={}
#要监控的服务名集合,{'ufw': 'service ufw start'}
for m in monitor_name:
monitor_map[m]='service '+m+' start' print(monitor_map) # print(time_now) # 显示进程,分别得到进程字典{'pid':'name'}和去重元祖()
def process_message():
# 进程字典,保存pid,进程名的键值对
proc_dict={}
# 进程列表,保存去重的进程名称
proc_list=set()
# psutil.Process(pid=4, name='System', started='2018-02-11 16:39:45')
for p in psutil.process_iter(attrs=['pid','name']):
proc_dict[p.info['pid']]=p.info['name']
proc_list.add(p.info['name'])
print(proc_list)
print(proc_dict) proc_stop = monitor_name - proc_list
#proc_stop:提取出来哪一个进程没有在当前操作系统下开启
if proc_stop:
#当前没有启动的这个进程集合不为空,有服务死掉了
for p in proc_stop:
print("正在重新启动%s"%p)
#取出每一个没有启动的服务名
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)
#post提交数据:提交的地址,提交的数据 if sys.platform.lower()=='linux':
os.system(monitor_map[p])
#函数不会给你返回值 proc_name = set() for p2 in psutil.process_iter(attrs=['pid','name']):
proc_name.add(p2.info['name'])
#操作系统下的所有进程名拿出来 if p in proc_name:
print("%s启动成功"%p)
p_status = '启动'
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:
print("%s启动失败"%p)
p_status = '停止'
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) if __name__ == '__main__': while True:
process_message()
上一篇:Vue 环境搭建之Hello World


下一篇:解决Spring MVC报No converter found for return value of type:class java.util.ArrayList问题