#! /usr/bin/env python
# -*- coding: utf-8 -*-

import os
import json
import time
import psutil
import urllib2
import requests
import datetime
import subprocess
import socket, fcntl, struct




def get_ip(ifname):  
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)  
    return socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', ifname[:15]))[20:24])

def post_data( url, para_dct):
        para_data = para_dct
        f = urllib2.urlopen(url,para_data)
        content = f.read()
        return content

def memory_stat():  
    mem = {}  
    f = open("/proc/meminfo")  
    lines = f.readlines()  
    f.close()  
    for line in lines:  
        if len(line) < 2: continue  
        name = line.split(':')[0]  
        var = line.split(':')[1].split()[0]  
        mem[name] = long(var) * 1024.0  
    mem['MemUsed'] = mem['MemTotal'] - mem['MemFree'] - mem['Buffers'] - mem['Cached']  
    return mem  
    
def _read_cpu_usage():  
    """从/proc/stat读取当前系统cpu使用率""" 
    try:  
        fd = open("/proc/stat", 'r')  
        lines = fd.readlines()  
 
    finally:  
        if fd:  
            fd.close()  

    for line in lines:  
        l = line.split()  
        if len(l) < 5:  
            continue 
        if l[0].startswith('cpu'):  
            return l  

    return []  

def get_cpu_usage():  
    """ 
    get cpu avg used by percent 
    """ 
    cpustr=_read_cpu_usage()  

    if not cpustr:  
        return 0 

    usni1=long(cpustr[1])+long(cpustr[2])+long(cpustr[3])+long(cpustr[5]) +long(cpustr[6])+long(cpustr[7])+long(cpustr[4])  
    usn1=long(cpustr[1])+long(cpustr[2])+long(cpustr[3])  

   #usni1=long(cpustr[1])+long(cpustr[2])+long(cpustr[3])+long(cpustr[4])  
 
   # self.sleep=2  
 
    time.sleep(2)  
    cpustr=_read_cpu_usage()

    if not cpustr:
        return 0

    usni2=long(cpustr[1])+long(cpustr[2])+float(cpustr[3])+long(cpustr[5])+long(cpustr[6])+long(cpustr[7])+long(cpustr[4])  
    usn2=long(cpustr[1])+long(cpustr[2])+long(cpustr[3])  
    cpuper=(usn2-usn1)/(usni2-usni1)  

    if 100*cpuper > 250:
        send_weixin_msg("服务器" + get_ip("eth1") + "CPU使用已超过250%,请速速关注")
    
    return 100*cpuper

def get_cpu_usage_2():  
    # 系统的CPU利用率
    psutil.cpu_percent(None)

    time.sleep(2)
    newdata = psutil.cpu_percent(None)
    if newdata > 250:
        send_weixin_msg("服务器" + get_ip("eth1") + "CPU使用已超过250%,请速速关注")
    
    return newdata

def cpu_stat():  
    cpu = []  
    cpuinfo = {}  
    f = open("/proc/cpuinfo")  
    lines = f.readlines()  
    f.close()
    for line in lines:
        if line == '\n':
            cpu.append(cpuinfo)
            cpuinfo = {}
        if len(line) < 2: continue
        name = line.split(':')[0].rstrip()  
        var = line.split(':')[1]  
        cpuinfo[name] = var  
    return cpu 

def load_stat():  
    loadavg = {}  
    f = open("/proc/loadavg")  
    con = f.read().split()  
    f.close()  
    loadavg['lavg_1']=con[0]  
    loadavg['lavg_5']=con[1]  
    loadavg['lavg_15']=con[2]  
    loadavg['nr']=con[3]  
    loadavg['last_pid']=con[4]  
    return loadavg
    
def uptime_stat():  
    uptime = {}  
    f = open("/proc/uptime")  
    con = f.read().split()  
    f.close()  
    all_sec = float(con[0])  
    MINUTE,HOUR,DAY = 60,3600,86400  
    uptime['day'] = int(all_sec / DAY )  
    uptime['hour'] = int((all_sec % DAY) / HOUR)  
    uptime['minute'] = int((all_sec % HOUR) / MINUTE)  
    uptime['second'] = int(all_sec % MINUTE)  
    uptime['Free rate'] = float(con[1]) / float(con[0])  
    return uptime

def net_stat():  
    net = []  
    f = open("/proc/net/dev")  
    lines = f.readlines()  
    f.close()  
    for line in lines[2:]:  
        con = line.split()  
        """ 
        intf = {} 
        intf['interface'] = con[0].lstrip(":") 
        intf['ReceiveBytes'] = int(con[1]) 
        intf['ReceivePackets'] = int(con[2]) 
        intf['ReceiveErrs'] = int(con[3]) 
        intf['ReceiveDrop'] = int(con[4]) 
        intf['ReceiveFifo'] = int(con[5]) 
        intf['ReceiveFrames'] = int(con[6]) 
        intf['ReceiveCompressed'] = int(con[7]) 
        intf['ReceiveMulticast'] = int(con[8]) 
        intf['TransmitBytes'] = int(con[9]) 
        intf['TransmitPackets'] = int(con[10]) 
        intf['TransmitErrs'] = int(con[11]) 
        intf['TransmitDrop'] = int(con[12]) 
        intf['TransmitFifo'] = int(con[13]) 
        intf['TransmitFrames'] = int(con[14]) 
        intf['TransmitCompressed'] = int(con[15]) 
        intf['TransmitMulticast'] = int(con[16]) 
        """  
        intf = dict(  
            zip(  
                ( 'interface','ReceiveBytes','ReceivePackets',  
                  'ReceiveErrs','ReceiveDrop','ReceiveFifo',  
                  'ReceiveFrames','ReceiveCompressed','ReceiveMulticast',  
                  'TransmitBytes','TransmitPackets','TransmitErrs',  
                  'TransmitDrop', 'TransmitFifo','TransmitFrames',  
                  'TransmitCompressed','TransmitMulticast' ),  
                ( con[0].rstrip(":"),int(con[1]),int(con[2]),  
                  int(con[3]),int(con[4]),int(con[5]),  
                  int(con[6]),int(con[7]),int(con[8]),  
                  int(con[9]),int(con[10]),int(con[11]),  
                  int(con[12]),int(con[13]),int(con[14]),  
                  int(con[15]),int(con[16]), )  
            )  
        )

        net.append(intf)  
    return net

def clean_disk():
    os.system('truncate --size 0 /usr/local/tomcat7/logs/catalina.out')
    os.system('truncate --size 0 /usr/local/tomcat7/bin/platform.log')
    os.system('find /usr/local/tomcat7/temp/ -mtime +2 | xargs rm -f')
    os.system('find /usr/local/tomcat7/logs/ -mtime +10 -type f ! -name "catalina.out" | xargs rm -f')
    os.system('find /usr/local/tomcat7/bin/platform.log* -mtime +10 | xargs rm -f')
    os.system('truncate --size 0 /usr/local/deploy/logs/*')

def disk_stat(clean):  
    hd={}  
    disk = os.statvfs("/")  
    hd['available'] = disk.f_bsize * disk.f_bavail  
    hd['capacity'] = disk.f_bsize * disk.f_blocks  
    hd['used'] = disk.f_bsize * disk.f_bfree

    available_percentage = disk.f_bavail * 1.00 / disk.f_blocks / 1.00
    if available_percentage < 0.1 and clean:
        clean_disk()
        disk_stat(False)
    elif available_percentage < 0.1:
        send_weixin_msg("服务器" + get_ip("eth1") + "硬盘使用已超过90%,请速速清理")
    return available_percentage

def process_stat():
    ret = os.popen('ps aux | grep tomcat').readlines()
    tomcat_exist = 0
    pid = []
    for line in ret:
        if "java" in line:
            tomcat_exist += 1
            params = line.split(" ")
            seq = 0
            for param in params:
                if len(param.lstrip()) > 0:
                    seq += 1
                    if seq == 2:
                        pid.append(param)
    if tomcat_exist != 1: 
        send_weixin_msg("服务器" + get_ip("eth1") + "tomcat进程异常,请速速处理")
        
    return tomcat_exist



def main():
    print disk_stat(True)
    print get_cpu_usage()
    print get_cpu_usage_2()
    print process_stat()
    # print net_stat()
    # print uptime_stat()
    # print load_stat()
    # print memory_stat()
    
    
main()

 

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐