zoukankan      html  css  js  c++  java
  • 用python监控Linux,CPU,内存,硬盘

    #!/usr/local/bin/python3.5
    #coding:utf-8
    import mailll, linecache, re, socket, os, time
    
    hostname = socket.gethostname()
    ip = socket.gethostbyname(hostname)
    
    def cpu_status():
        with open("/proc/loadavg", 'rt') as f:
            data = f.read().split()
        if float(data[2]) > 0.7:
            with open("/home/cpustatus.txt", 'wt') as f:
                print("notice : 
            Hostname : %s
            IP : %s
    
            The CPU loadavg will overload : %s" % (hostname, ip, data[2]), file = f) 
            mailll.send_mail("/home/cpustatus.txt")    
    
    def memory_status():
        theline = linecache.getline(r'/proc/meminfo', 2)
        mem_free_num = "".join(re.findall(r"[0-9]", theline))
     
        if (int(mem_free_num) / 1000) < 100:
            with open("/home/memory.txt", 'wt') as f:
                print("notice : 
            Hostname : %s
            IP : %s
    
            Insufficient free memory : %s" % (hostname, ip, str(int(mem_free_num) / 1000) + "M"), file = f)
            mailll.send_mail("/home/memory.txt") 
    
    def disk_status():
        os.system("df -hT |grep ext4 |awk -F '[ %]+' ' {if($6 >= 70) print $6}' |wc -l > /home/diskstatus.txt")
        diskcount = int(linecache.getline(r'/home/diskstatus.txt', 1))
        if diskcount >= 1 :
            
            with open("/home/diskstatus.txt", 'wt') as f:
                print("notice : 
            Hostname : %s
            IP : %s
    " % (hostname, ip), file = f)            
            os.system("echo 'Hard disk capacity is insufficient :' >> /home/diskstatus.txt")
            os.system("df -hT |grep 'ext4|Filesystem' >> /home/diskstatus.txt")
            mailll.send_mail('/home/diskstatus.txt')
    
    
    try:
        cpu_status()
        time.sleep(2)
        memory_status()
        time.sleep(2)
        disk_status()
    except Exception as e:
        print("program is error!!!")
    

    新手,自我感觉就是功能实现了,代码实在不怎么样,但是还是记录下来,希望大家多多指出不足,以后随着学习的深入,希望能做的更好!

    END!!!

  • 相关阅读:
    ajax上传文件
    nginx location指令详解
    总结php删除html标签和标签内的内容的方法
    useBuiltIns: 'usage'
    uni-app如何页面传参数的几种方法总结
    基于 schema 的数据校验
    canvas时点击事件和长按冲突
    vue 下载文件流,后台是get方式 ,并且导出出现excel乱码问题
    uni-app canvas 实现文字居中
    git reflog 回退
  • 原文地址:https://www.cnblogs.com/changbo/p/6011549.html
Copyright © 2011-2022 走看看