歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python監控CPU情況

Python監控CPU情況

日期:2017/3/1 9:39:30   编辑:Linux編程

Python監控CPU情況

#!/usr/bin/env python
# -*- coding=utf-8 -*-
#Using GPL v2.7
#Author: [email protected]
#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

《Python核心編程 第二版》.(Wesley J. Chun ).[高清PDF中文版] http://www.linuxidc.com/Linux/2013-06/85425.htm

《Python開發技術詳解》.( 周偉,宗傑).[高清PDF掃描版+隨書視頻+代碼] http://www.linuxidc.com/Linux/2013-11/92693.htm

Python腳本獲取Linux系統信息 http://www.linuxidc.com/Linux/2013-08/88531.htm

在Ubuntu下用Python搭建桌面算法交易研究環境 http://www.linuxidc.com/Linux/2013-11/92534.htm

Python 的詳細介紹:請點這裡
Python 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved