window-server服务器监控自动化(cpu、mem、disk)-->钉钉报警

一、windows-server服务太多,cpu、disk异常等如何报警?服务器down还没有发现 业务停止 损失巨大。接下来看我骚操作
二、安装相应的库(自行安装,这里用的是python3.8,pycharm)

import psutil
import requests
import time
import datetime
import socket
import os

三、创建空字典,列表

cpu_info={'user':0,  'system':0,  'idle':0,   'percent':0}
memory_info={'total':0, 'available':0,  'percent':0,  'used':0, 'free':0}
disk_id = []
disk_total = []
disk_used = []
disk_free = []
disk_percent = []

四、cpu_info函数

def get_cpu_info():
    cpu_times = psutil.cpu_times()
    cpu_info['user'] = cpu_times.user
    cpu_info['system'] = cpu_times.system
    cpu_info['idle'] = cpu_times.idle
    cpu_info['percent'] = psutil.cpu_percent(interval=2)
psutil.cpu_times():查看cpu完整信息
cpu_times.user:查看用户的cpu时间比
cpu_times.system:查看系统信息
cpu_times.idle:每个cpu进入idle的时间
psutil.cpu_percent(interval=2):cpu使用率时间间隔(默认是1)

五、get_memory_info函数

def get_memory_info():
    mem_info = psutil.virtual_memory()
    memory_info['total'] = mem_info.total
    memory_info['available'] = mem_info.available
    memory_info['percent'] = mem_info.percent
    memory_info['used'] = mem_info.used
    memory_info['free'] = mem_info.free
psutil.virtual_memory:获取系统内存的使用情况
mem_info.total:total表示内存总的大小
mem_info.percent:percent表示实际已经使用的内存占比。
mem_info.used:used表示已经使用的内存
 mem_info.free:空闲内存

六、def get_disk_info函数

def get_disk_info():
    for id in psutil.disk_partitions():
        if 'cdrom' in id.opts or id.fstype =='':
            continue
        disk_name = id.device.split(':')
        s = disk_name[0]
        disk_id.append(s)
        disk_info = psutil.disk_usage(id.device)
        disk_total.append(disk_info.total)
        disk_used.append(disk_info.used)
        disk_free.append(disk_info.free)
        disk_percent.append(disk_info.percent)
psutil.disk_partitions:获取磁盘分区信息
psutil.disk_usage:获取路径所在磁盘的使用情况
进行分割,提取磁盘id,添加到list中

七、send_post函数

def send_post():
    hostName = socket.gethostname()
    url='https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxxxxxx'
    headers = {
        "Content-Type": "application/json"
    }
    form_data={"msgtype": "text",
         "text": {
             "content": hostName+"服务器异常,请检查!"
                }
         }
    html=requests.post(url,headers=headers,json=form_data).text
    return html
钉钉接口post请求
钉钉API接口文档:https://developers.dingtalk.com/document/app/develop-enterprise-internal-robots/title-mno-3qd-5f9
自己开发一个也很简单,md5加签等,看文档瞬间明白
我这里自定义机器人接入

在这里插入图片描述
在这里插入图片描述

八、fun_timer函数

def fun_timer():
    print('当前检测时间为:',time.strftime('%Y-%m-%d %X',time.localtime()))
    print("当前时间:", datetime.datetime.now())
    list1 = []
    list2 = []
    a = []
    get_cpu_info()
    cpu_status = cpu_info['percent']
    list1.append('cpu usage is:%s%%'%cpu_status)
    get_memory_info()
    mem_status = memory_info['percent']
    f_monitor = open('C:\\vbs\\monitor.conf', 'r', encoding='utf-8')
    f_monitor_lines = f_monitor.readlines()

    for f_line_num, f_monitor_line in enumerate(f_monitor_lines):
        tup = f_monitor_line.rstrip('\n').rstrip().split('\t')
        if '=' in tup[0]:  # 刨除异常状况
            temp = tup[0].split('=')  # 读取每一项元素
            if temp[0] == 'cpu_used':
                cpu_used = temp[1]
                a.append(cpu_used)
                print("read cpu_used:", cpu_used)
            elif temp[0] == 'mem_used':
                mem_used = temp[1]
                a.append(mem_used)
                print("read mem_used:", mem_used)
    line = [float(x) for x in a]

    if cpu_status > line[0] and mem_status > line[1]:
        send_post()
        print("检测成功!!!")

    list1.append('memory usage is:%s%%'%mem_status)
    get_disk_info()
    if len(disk_id) > 3:
        li=list(set(disk_id))
        for i in range(len(li)):
            list2.append('%s:'%li[i]+'disk usage is:%s%%'%(100 - disk_percent[i]))
    else:
        for i in range(len(disk_id)):
            list2.append('%s:' % disk_id[i] + 'disk usage is:%s%%' % (100 - disk_percent[i]))

    a=list1+list2
    # print(a)
    path = 'C:\\vbs\\'
    name = "监控"
    os.path.exists(path)
    t = os.path.exists(path + name)
    if not t:
        os.makedirs(path + name)
        print("目录新建成功")
    else:
        print("文件已存在")

    shijian=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    print(shijian)
    with open(r'C:\vbs\监控\监控信息.txt','a+') as f:
        f.write(shijian+'\n')
        f.close()
    for x in a:
        print(x)
        with open(r'C:\vbs\监控\监控信息.txt','a+') as f:
            f.write(x+'\n')
            f.close()
    pt='========================================='
    with open(r'C:\vbs\监控\监控信息.txt','a+') as f:
        f.write(pt+'\n')
        f.close()
参数配置我外置的,方便更好管理设置
写入目录,文件

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
八、主函数

if  __name__    ==   '__main__':
    # 检测时间间隔
    timer_interval = 60
    while True:
        print("检测时间间隔:%s秒" % timer_interval)
        fun_timer()
        time.sleep(timer_interval)

在这里插入图片描述
九、打包成exe放入服务器
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
查看详细信息:
在这里插入图片描述
多多关注,后续更精彩,上高速不翻车。

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值