python-检测cpu负载

2023-01-31 02:01:56 python 负载 检测

      近期研究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种方法效果一样,脚本很简单,有好方法的大神,开源出来,互相学习

相关文章