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

  • 相关阅读:
    redux-simple 简化版的redux
    react服务端渲染(同构)
    使用systemd管理程序进程
    使用Dockerfile构建镜像
    centos7使用supermin制作centos7的docker镜像包
    DNS-dnsmasq安装配置
    kubernetes-部署(单机,使用证书)
    DNS-bind+namedmanager安装
    python3第一个脚本(hello world!)
    Python3 基础语法
  • 原文地址:https://www.cnblogs.com/changbo/p/6011549.html
Copyright © 2011-2022 走看看