Python监控CPU情况

Python监控CPU情况

#!/usr/bin/env python
# -*- coding=utf-8 -*-
#Using GPL v2.7
#Author: leexide@126.com
#Python监控CPU情况
"""
1、实现原理:通过SNMP协议获取系统信息,再进行相应的计算和格式化,最后输出结果
2、特别注意:被监控的机器上需要支持snmp。yum install -y net-snmp*安装
"""

#!/usr/bin/python
import os
def getAllitems(host, oid):
        sn1 = os.popen('snmpwalk -v 2c -c public ' + host + ' ' + oid + '|grep Raw|grep Cpu|grep -v Kernel').read().split('\n')[:-1]
        return sn1
                                                               
def getDate(host):
        items = getAllitems(host, '.1.3.6.1.4.1.2021.11')
                                                               
        date = []
        rate = []
        cpu_total = 0
        #us = us+ni, sy = sy + irq + sirq
        for item in items:
                float_item = float(item.split(' ')[3])
                cpu_total += float_item
                if item == items[0]:
                        date.append(float(item.split(' ')[3]) + float(items[1].split(' ')[3]))
                elif item == item[2]:
                        date.append(float(item.split(' ')[3] + items[5].split(' ')[3] + items[6].split(' ')[3]))
                else:
                        date.append(float_item)
                                                               
        #calculate cpu usage percentage
        for item in date:
                rate.append((item/cpu_total)*100)
                                                               
        mean = ['%us','%ni','%sy','%id','%wa','%cpu_irq','%cpu_sIRQ']
                                                               
        #calculate cpu usage percentage
        result = map(None,rate,mean)
        return result
                                                               
if __name__ == '__main__':
        hosts = ['192.168.10.1','192.168.10.2']
        for host in hosts:
                print '==========' + host + '=========='
                result = getDate(host)
                print 'Cpu(s)',
                #print result
                for i in range(5):
                        print ' %.2f%s' % (result[i][0],result[i][1]),
                print
                print

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值