python监控服务器信息
本文转载自http://www.linuxtone.org/thread-29256-1-1.html 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 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 #coding:utf-8 #by_wangyi #by:QQ917611 #QQ群:251289157 import psutil import time import os import sys import re stats = [ 0 , 1 ] stoptimes = 2 if len (sys.argv)> 1 : interface = sys.argv[ 1 ] else : interface = 'eth0' class Monitor: def __init__( self ,user_uid,stoptime): self .user_uid = user_uid self .stoptime = stoptime if user_uid = = 0 : print "请使用root用户运行此脚本" exit() def meminfo( self ,used_vm,free_vm,buffers,cached): total = psutil.virtual_memory().total / 1024 / 1024 used = used_vm - (buffers + cached) free = total - used print "totalmem:%sM" % total print "usedmem:%sM" % used print "freemem:%sM" % free def diskinfo( self ): list = [] for i in psutil.disk_partitions(): list .append(i[ 1 ]) for k in range ( len ( list )): total = "%-15s分区\ttotal:%s" % ( list [k],psutil.disk_usage( list [k]).total / 1024 / 1024 / 1024 ) used = "used:%s" % (psutil.disk_usage( list [k]).used / 1024 / 1024 / 1024 ) free = "free:%s" % (psutil.disk_usage( list [k]).free / 1024 / 1024 / 1024 ) print "%sG\t%sG\t%sG" % (total,used,free) def cpuinfo( self ): with open ( '/proc/loadavg' )asf: loadavg = f.read() print "5分钟cpuload:%s" % (loadavg.split()[ 0 ]) print "10分钟cpuload:%s" % (loadavg.split()[ 1 ]) print "15分钟cpuload:%s" % (loadavg.split()[ 2 ]) print "当前运行proc:%s" % (loadavg.split()[ 3 ].split( '/' )[ 0 ]) print "最后运行pid:%s" % (loadavg.split()[ 4 ]) print '当前cpu%s' % (psutil.cpu_percent()) def flowinfo( self ): f = open ( '/proc/net/dev' , 'r' ).readlines() for i in f: if re.search(interface,i): rx = i.split( ':' )[ 1 ].split()[ 0 ] tx = i.split()[ 8 ] stats[ 0 ] = rx stats[ 1 ] = tx used_vm = psutil.virtual_memory().used / 1024 / 1024 free_vm = psutil.virtual_memory().free / 1024 / 1024 buffers = psutil.virtual_memory().buffers / 1024 / 1024 cached = psutil.virtual_memory().cached / 1024 / 1024 if __name__ = = '__main__' : user_uid = os.geteuid() stoptime = 2 task = Monitor(user_uid,stoptime) print "servermeminfo:\n" task.meminfo(used_vm,free_vm,buffers,cached) print "==================================" print "serverdiskinfo:\n" task.diskinfo() print "===================================" print "servercpuinfo:\n" task.cpuinfo() print "===================================" print "serverflowinfo:\n" task.flowinfo() RX_one = float (stats[ 0 ]) TX_one = float (stats[ 1 ]) time.sleep(stoptimes) task.flowinfo() RX_two = float (stats[ 0 ]) TX_two = float (stats[ 1 ]) RX_rate = round ( float (RX_two - RX_one) / 1024 , 2 ) TX_rate = round ( float (TX_two - TX_one) / 1024 , 2 ) print time.strftime( "%Y-%m-%d%H:%M:%S" ), 'RXbytes=' ,RX_rate, 'KB' print time.strftime( "%Y-%m-%d%H:%M:%S" ), 'TXbytes=' ,TX_rate, 'KB'