本文转载自http://www.linuxtone.org/thread-29256-1-1.html
# 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 "total mem: %sM" %total print "used mem: %sM" %used print "free mem: %sM" %free def diskinfo(self): list = [] for i in psutil.disk_partitions(): list.append(i[1]) for k in range(len(list)): total= "%-15s 分区\t total: %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') as f: loadavg = f.read() print "5分钟 cpu load: %s" %(loadavg.split( )[0]) print "10分钟cpu load: %s" %(loadavg.split( )[1]) print "15分钟cpu load: %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 "server meminfo:\n" task.meminfo(used_vm,free_vm,buffers,cached) print "==================================" print "server diskinfo:\n" task.diskinfo() print "===================================" print "server cpuinfo:\n" task.cpuinfo() print "===================================" print "server flowinfo:\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'