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!!!

  • 相关阅读:
    【ES6】函数的扩展
    NSFileManger使用介绍
    委托,曾将让我头疼难以理解
    【HDOJ】1914 The Stable Marriage Problem
    MySQL修改配置优化插入性能
    MySQL配置文件的编码问题
    MyBatis批量更新时提示"You have an error in your SQL syntax"
    MyBatis批量更新返回受影响数
    log4j.properties配置说明
    删除Win10的OneDrive
  • 原文地址:https://www.cnblogs.com/changbo/p/6011549.html
Copyright © 2011-2022 走看看