zoukankan      html  css  js  c++  java
  • python中用psutil模块,yagmail模块监控CPU、硬盘、内存使用,阈值后发送邮件


    import yagmail
    import psutil
    def sendmail(subject,contents):
    #连接邮箱服务器
    yag = yagmail.SMTP(user='邮箱名称@163.com',password='邮箱客户端授权密码',host='smtp.163.com')
    #发送邮件
    yag.send(to='收件方邮箱地址',subject=subject, contents=contents)
    #断开连接
    yag.close()

    def cpu_info():
    cpu = psutil.cpu_percent(1)
    return cpu

    def mem_info():
    mem = psutil.virtual_memory()
    total_mem = int(mem[0]/1024/1024)
    free_mem = int(mem[1]/1024/1024)
    percent_mem = mem[2]
    used_mem = int(mem[3]/1024/1024)
    mem_dict = {
    'total_mem':total_mem,
    'free_mem':free_mem,
    'percent_mem':percent_mem,
    'used_mem':used_mem
    }
    return mem_dict

    def disk_info():
    disk = psutil.disk_usage('c:')
    total_disk = int(disk[0]/1024/1024/1024)
    used_disk = int(disk[1]/1024/1024/1024)
    free_disk = int(disk[2]/1024/1024/1024)
    percent_disk = disk[3]
    disk_dict = {
    'total_disk':total_disk,
    'used_disk':used_disk,
    'free_disk':free_disk,
    'percent_disk':percent_disk
    }
    return disk_dict

    def main():
    cpu = cpu_info()
    mem = mem_info()
    disk = disk_info()
    msg = '''
    cpu利用率:%s%%
    内存总大小:%sM
    内存剩余大小:%sM
    内存使用大小:%sM
    内存使用率:%s%%
    硬盘总大小:%sG
    硬盘使用大小:%sG
    硬盘剩余大小:%sG
    硬盘使用率:%s%%
    ''' % (cpu,mem.get('total_mem'),mem.get('free_mem'),mem.get('used_mem'),mem.get('percent_mem'),disk.get('total_disk'),disk.get('used_disk'),disk.get('free_disk'),disk.get('percent_disk'))
    if cpu > 1:
    print('cpu过高')
    sendmail('cpu报警',msg)
    else:
    print('cpu正常')

    if __name__ == '__main__':
    main()
  • 相关阅读:
    jprofiler配置
    Nginx编译安装
    WebBench的安装与使用
    你经常看到却经常忽视的__init__.py有什么用?
    彻底搞懂Python 中的 import 与 from import
    实现有过期时间的LRU缓存
    实现函数调用结果的 LRU 缓存
    elasticsearch Routing 路由详解
    Elasticsearch _reindex 接口来重新索引数据到新索引,使用新的配置
    浏览器操作elasticsearch别名
  • 原文地址:https://www.cnblogs.com/xuezhihen1901/p/10764501.html
Copyright © 2011-2022 走看看