python监控系统资源

监控网卡流量


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38


#!/usr/bin/python

import re

import os

#get SNMP-MIB2 of the devices

def getAllitems(host,oid):

        sn1 = os.popen(‘snmpwalk -v 2c -c public ‘ + host + ‘ ‘ + oid).read().split(‘\n‘)[:-1]

        return sn1

                                                                                         

#get network device

def getDevices(host):

        device_mib = getAllitems(host,‘RFC1213-MIB::ifDescr‘)

        device_list = []

        for item in device_mib:

                if re.search(‘eth‘,item):

                        device_list.append(item.split(‘:‘)[3].strip())

        return device_list

                                                                                         

#get network date

def getDate(host,oid):

        date_mib = getAllitems(host,oid)[1:]

        date = []

        for item in date_mib:

                byte = float(item.split(‘:‘)[3].strip())

                date.append(str(round(byte/1024,2)) + ‘ KB‘)

        return date

                                                                                         

if __name__ == ‘__main__‘:

        hosts = [‘192.168.30.111‘,‘192.168.30.112‘]

        for host in hosts:

                device_list = getDevices(host)

                                                                                         

                inside = getDate(host,‘IF-MIB::ifInOctets‘)

                outside = getDate(host,‘IF-MIB::ifOutOctets‘)

                                                                                         

                print ‘==========‘ + host + ‘==========‘

                for in range(len(inside)):

                        print ‘%s : RX: %-15s   TX: %s ‘ % (device_list[i], inside[i], outside[i])

                print

监控内存(swap)使用率


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35


#!/usr/bin/python

import os

def getAllitems(host, oid):

        sn1 = os.popen(‘snmpwalk -v 2c -c public ‘ + host + ‘ ‘ + oid).read().split(‘\n‘)[:-1]

        return sn1

                                                                           

def getSwapTotal(host):

        swap_total = getAllitems(host, ‘UCD-SNMP-MIB::memTotalSwap.0‘)[0].split(‘ ‘)[3]

        return swap_total

                                                                           

def getSwapUsed(host):

        swap_avail = getAllitems(host, ‘UCD-SNMP-MIB::memAvailSwap.0‘)[0].split(‘ ‘)[3]

        swap_total = getSwapTotal(host)

        swap_used = str(round(((float(swap_total)-float(swap_avail))/float(swap_total))*100 ,2)) + ‘%‘

        return swap_used

                                                                           

def getMemTotal(host):

        mem_total = getAllitems(host, ‘UCD-SNMP-MIB::memTotalReal.0‘)[0].split(‘ ‘)[3]

        return mem_total

                                                                           

def getMemUsed(host):

        mem_total = getMemTotal(host)

        mem_avail = getAllitems(host, ‘UCD-SNMP-MIB::memAvailReal.0‘)[0].split(‘ ‘)[3]

        mem_used = str(round(((float(mem_total)-float(mem_avail))/float(mem_total))*100 ,2)) + ‘%‘

        return mem_used

                                                                           

if __name__ == ‘__main__‘:

        hosts = [‘192.168.30.111‘,‘192.168.30.112‘]

        print "Monitoring Memory Usage"

        for host in hosts:

                mem_used = getMemUsed(host)

                swap_used = getSwapUsed(host)

                print ‘==========‘ + host + ‘==========‘

                print ‘Mem_Used = %-15s   Swap_Used = %-15s‘ % (mem_used, swap_used)

                print

监控系统负载


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19


#!/usr/bin/python

import os

def getAllitems(host, oid):

        sn1 = os.popen(‘snmpwalk -v 2c -c public ‘ + host + ‘ ‘ + oid).read().split(‘\n‘)

        return sn1

                                                                    

def getload(host,loid):

        load_oids = ‘1.3.6.1.4.1.2021.10.1.3.‘ + str(loid)

        return getAllitems(host,load_oids)[0].split(‘:‘)[3]

                                                                    

if __name__ == ‘__main__‘:

        hosts = [‘192.168.30.111‘,‘192.168.30.112‘]

        #check_system_load

        print ‘==============System Load==============‘

        for host in hosts:

                load1 = getload(host, 1)

                load10 = getload(host, 2)

                load15 = getload(host, 3)

                print ‘%s load(1min): %s ,load(10min): %s ,load(15min): %s‘ % (host,load1,load10,load15)

监控CPU


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44


#!/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.30.111‘,‘192.168.30.112‘]

        for host in hosts:

                print ‘==========‘ + host + ‘==========‘

                result = getDate(host)

                print ‘Cpu(s)‘,

                #print result

                for in range(5):

                        print ‘ %.2f%s‘ % (result[i][0],result[i][1]),

                print

                print

监控磁盘


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64


#!/usr/bin/python

import re

import os

def getAllitems(host,oid):

        sn1 = os.popen(‘snmpwalk -v 2c -c public ‘ + host + ‘ ‘ + oid).read().split(‘\n‘)[:-1]

        return sn1

                                                            

def getDate(source,newitem):

        for item in source[5:]:

                newitem.append(item.split(‘:‘)[3].strip())

        return newitem

                                                            

def getRealDate(item1,item2,listname):

        for in range(len(item1)):

                listname.append(int(item1[i])*int(item2[i])/1024)

        return listname

                                                            

def caculateDiskUsedRate(host):

        hrStorageDescr = getAllitems(host, ‘HOST-RESOURCES-MIB::hrStorageDescr‘)

        hrStorageUsed = getAllitems(host, ‘HOST-RESOURCES-MIB::hrStorageUsed‘)

        hrStorageSize = getAllitems(host, ‘HOST-RESOURCES-MIB::hrStorageSize‘)

        hrStorageAllocationUnits = getAllitems(host, ‘HOST-RESOURCES-MIB::hrStorageAllocationUnits‘)

                                                            

        disk_list = []

        hrsused = []

        hrsize = []

        hrsaunits = []

                                                            

        #get disk_list

        for item in hrStorageDescr:

                if re.search(‘/‘,item):

                        disk_list.append(item.split(‘:‘)[3])

        #print disk_list      

                                                            

        getDate(hrStorageUsed,hrsused)

        getDate(hrStorageSize,hrsize)

        #print getDate(hrStorageAllocationUnits,hrsaunits)

                                                            

        #get hrstorageAllocationUnits

        for item in hrStorageAllocationUnits[5:]:

                hrsaunits.append(item.split(‘:‘)[3].strip().split(‘ ‘)[0])

        #caculate the result

        #disk_used = hrStorageUsed * hrStorageAllocationUnits /1024 (KB)

        disk_used = []

        total_size = []

        disk_used = getRealDate(hrsused,hrsaunits,disk_used)

        total_size = getRealDate(hrsize,hrsaunits,total_size)

                                                            

        diskused_rate = []

        for in range(len(disk_used)):

                diskused_rate.append(str(round((float(disk_used[i])/float(total_size[i])*100), 2)) + ‘%‘)

                                                            

        return diskused_rate,disk_list

                                                            

if __name__ == ‘__main__‘:

        hosts = [‘192.168.30.111‘,‘192.168.30.112‘]

        for host in hosts:

                result = caculateDiskUsedRate(host)

                diskused_rate = result[0]

                partition = result[1]

                print "==========",host,‘==========‘

                for in range(len(diskused_rate)):

                        print ‘%-20s used: %s‘ % (partition[i],diskused_rate[i])

                print

时间: 2025-01-15 01:40:14

python监控系统资源的相关文章

python监控系统资源最终版(CPU,内存,磁盘等)

#!/usr/bin/env python3 #-*- coding:utf-8 -*- #create at 2018-12-07 'this is a system monitor scripts' __author__="yjt" import os import time import sys import datetime import socket import psutil import re import json #以下是变量值,自己定义 CPUT = 2 #计算CP

python监控linux性能以及进程消耗的性能

ExecutorService 建立多线程线程池的步骤: 线程池的作用: 线程池作用就是限制系统中执行线程的数量. 根据系统的环境情况,可以自动或手动设置线程数量,达到运行的最佳效果:少了浪费了系统资源,多了造成系统拥挤效率不高.用线程池控制线程数量,其他线程排队等候.一个任务执行完毕,再从队列的中取最前面的任务开始执行.若队列中没有等待进程,线程池的这一资源处于等待.当一个新任务需要运行时,如果线程池中有等待的工作线程,就可以开始运行了:否则进入等待队列. 为什么要用线程池: 1.减少了创建和

用python监控您的window服务

原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 .作者信息和本声明.否则将追究法律责任.http://world77.blog.51cto.com/414605/782935 最近比较烦,研发给的pc服务版本在虚拟机上已经开始给客户使用了,服务老是莫名的死翘翘,客户不停的电话给我,搞的我心情很差,于是在一个下午,静下心来,用python写了个简单的监控进程的脚本,当发现进程消失的时候,立即调用服务,开启服务... 脚本的工作原理是这样的:脚本读取配置文件,读取预先配置好的调用系统

Linux安装rpc监控系统资源

1.rpc服务需rsh的支持,一般情况下rsh已安装.rpm -qa rsh查看.2.右键另存为http://heanet.dl.sourceforge.net/sourceforge/rstatd/rpc.rstatd-4.0.1.tar.gz下载rpc.rstatd-4.0.1.tar.gz.3.执行以下命令解压和安装tar zxvf rpc.rstatd-4.0.1.tar.gzcd rpc.rstatd-4.0.1./configure   //配置make          //编译m

【Python运维脚本】Python监控内存(swap)的使用率

#!/usr/bin/env python # -*- coding=utf-8 -*- #Using GPL v2.7 #Author: [email protected] #Python监控内存(swap)的使用率 ''' 1.实现原理:通过SNMP协议获取系统信息,再进行相应的计算和格式化,最后输出结果 2.特别注意:被监控的机器上需要支持snmp.yum install -y net-snmp*安装 ''' #!/usr/bin/python import os def getAllit

Python 监控nginx服务是否正常

Python 监控nginx服务是否正常 #!/usr/bin/env python import os, sys, time from time import strftime while True: try: ret = os.popen('ps -C nginx -o pid,cmd').readlines() if len(ret) <2: os.system("service nginx start") sys.exit(0) except Exception,ex:

【Python运维脚本】Python监控磁盘

#!/usr/bin/env python # -*- coding=utf-8 -*- #Using GPL v3.3 #Author: [email protected] #Python监控磁盘 """ 1.实现原理:通过SNMP协议获取系统信息,再进行相应的计算和格式化,最后输出结果 2.特别注意:被监控的机器上需要支持snmp.yum install -y net-snmp*安装 """ #!/usr/bin/python import

【Jmeter如何监控系统资源】

用Jmeter做性能测试的时候,希望监控Linux/windows系统下的系统资源,包括CPU.内存等.但是直接解压下载的Jmeter是没有这项功能的,需要我们安装插件:JMeterPlugins-Standard-1.4.0.zip具体步骤如下: 1.下载JMeterPlugins-Standard-1.4.0.zip,将其解压. 2.将其解压文件中的JMeterPlugins-Standard.jar复制到Jmeter\apache-jmeter-3.1\lib\ext目录下. 3.重新启动

【Python运维脚本】Python监控网卡流量

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