python写监控脚本_python 写一个类似于top的监控脚本

#!/usr/bin/env python#-*- coding:utf-8 -*-##############################__author__ = 'webber' ##create at 2016/12/12 ##############################

importosimportsysimporttimedefcpuinfo():"""get cpuinfo from '/proc/stat' and

calculate the percentage of the cpu occupy."""f= open('/proc/stat','r')

cpu=f.readline()

f.close()#print "cpuinfo: ", cpu

cpu = cpu.split(" ")

total=0

usr= float(cpu[2]) #用户态cpu占用率

_sys = float(cpu[4]) #内核态cpu占用率

for info incpu:ifinfo.isdigit():

total+=float(info)print '\033[31mcpu info: \033[0m',print 'usr: %.5f%%' % ((usr/total)*100),print 'sys: %.5f%%' % ((_sys/total)*100)defmeminfo():"""get meminfo from '/proc/meminfo' and

calculate the percentage of the mem occupy

used = total - free - buffers - cached"""f= open('/proc/meminfo','r')

mem=f.readlines()

f.close()#print "meminfo", mem

total, free, buffers, cached =0, 0, 0, 0for info inmem:

mem_item=info.lower().split()#print mem_item

if mem_item[0] == 'memtotal:':

total= float(mem_item[1])if mem_item[0] == 'memfree:':

free= float(mem_item[1])if mem_item[0] == 'buffers:':

buffers= float(mem_item[1])if mem_item[0] == 'cached:':

cached= float(mem_item[1])

used= total - free - buffers -cachedprint "\033[31mmeminfo: \033[0m",print "total: %.2f GB" % (total/1024/1024),print "used: %.5f%%" % (used/total)defnetinfo():"""get real-time bandwidth"""f= open('/proc/net/dev','r')

net=f.readlines()

f.close()

net_item=[]for info innet:if info.strip().startswith("eth0"):

net_item=info.strip().split()break

#print net_item

recv = float(net_item[1])

send= float(net_item[9])#print "recv:%s " % recv

#print "send:%s " % send

time.sleep(1)

f2= open('/proc/net/dev','r')

_net=f2.readlines()

f2.close()

_net_item=[]for info in_net:if info.strip().startswith("eth0"):

_net_item=info.strip().split()breakrecv_2= float(_net_item[1])

send_2= float(_net_item[9])#print "recv_2:%s " % recv_2

#print "send_2:%s " % send_2

print "\033[31m network info: \033[0m"

print "received: %.3f Kb/s" % (recv_2/1024 - recv/1024)print "transmit: %.3f kb/s" % (send_2/1024 - send/1024)defloadavg():pass

defdisk():pass

if __name__ == '__main__':whileTrue:try:

os.system('clear')

cpuinfo()print "=============================================="meminfo()print "##############################################"netinfo()

time.sleep(5)except KeyboardInterrupt, e: #这里也可以用信号函数来处理

print ''

print "BYE-BYE"sys.exit(0)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值