码迷,mamicode.com
首页 > 编程语言 > 详细

python-检测cpu负载

时间:2014-12-15 21:59:24      阅读:247      评论:0      收藏:0      [点我收藏+]

标签:python-检测cpu负载

      近期研究nagios,特意写了检测cpu负载的python脚本(有借鉴网上资料),顺道练练python脚本,以下采用2种方法获取cpu负载。

1、读取cpu负载文件:

#!/usr/bin/env python
#-*- coding:utf-8 -*-
‘‘‘cpu负载检测 for nagios‘‘‘
import sys
def check_load():
    loadf=open(‘/proc/loadavg‘,‘r‘)
    allavg=loadf.readline()
    load5avg=float(allavg.split()[0])
    load10avg=float(allavg.split()[1])
    load15avg=float(allavg.split()[2])
    loadf.close()
    print load5avg
    n=0
    cpunf=open(‘/proc/cpuinfo‘,‘r‘)
    for i in cpunf.readlines():
        if i.split(‘:‘)[0].strip() == ‘processor‘:
            n+=1
    cpunf.close()
    if load5avg > n:
        print "critical - load average:%.2f,%.2f,%.2f" %(load5avg,load10avg,load15avg)
        sys.exit(2)
    else:
        print "OK - load average:%.2f,%.2f,%.2f" %(load5avg,load10avg,load15avg)
        sys.exit(0)

if __name__ == ‘__main__‘:
    check_load()


2、调用python的os模块获取cpu负载:

#!/usr/bin/env python
#-*- coding:utf-8 -*-
‘‘‘cpu负载检测 for nagios‘‘‘
import os,sys
def check_load():
    (d1,d2,d3)=os.getloadavg()
    print d1
    n=0
    cpunf=open(‘/proc/cpuinfo‘,‘r‘)
    for i in cpunf.readlines():
        if i.split(‘:‘)[0].strip() == ‘processor‘:
            n+=1
    cpunf.close()
    if d1 > n:
        print "critical - load average:%.2f,%.2f,%.2f" %(d1,d2,d3)
        sys.exit(2)
    else:
        print "OK - load average:%.2f,%.2f,%.2f" %(d1,d2,d3)
        sys.exit(0)

if __name__ == ‘__main__‘:
    check_load()


备注:2种方法效果一样,脚本很简单,有好方法的大神,开源出来,互相学习!

本文出自 “蜗牛的家” 博客,请务必保留此出处http://winters.blog.51cto.com/5617866/1590197

python-检测cpu负载

标签:python-检测cpu负载

原文地址:http://winters.blog.51cto.com/5617866/1590197

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!