zoukankan      html  css  js  c++  java
  • python 写一个类似于top的监控脚本

    最近老板给提出一个需要,项目需求大致如下:

     
       1、用树莓派作为网关,底层接多个ZigBee传感节点,网关把ZigBee传感节点采集到的信息通过串口接收汇总,并且发送给上层的HTTP Server;
    2、要有数据的反向控制通道,即网关与Server间要保持长连接,采用websocket实现,以此实现给ZigBee传感节点发送控制命令,来实现对ZigBee节点的远程配置操作;
    3、树莓派网关本身要与上层Server实现交互,上层Server能够看到网关实时的cpu、内存以及网络上行与下行的带宽等等;

    前两条需求在前一段时间已经基本实现,等后续有时间完善之后在整理,今天记录一下第三条的实现过程。

    感觉第三条需求很像目前公司用到的监控系统的一个小的底层实现,因为前几天无聊刚好搭了个zabbix的环境玩了玩,感觉老板的需求在前端上好像就是类似于zabbix Server上的那种展现形式,但是用zabbix实在感觉不够灵活,其实我也用不明白,只能实现一个类似于top工具的监控脚本吧,先把实时的cpu、内存、网络流量等信息在本地表现出来,等待后续和Server端的朋友联调再说,代码如下:

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    #############################
    #__author__ = 'webber'      #
    #create at 2016/12/12       #
    #############################
    import os
    import sys
    import time
    
    def cpuinfo():
        """
        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 in cpu:
            if info.isdigit():
                total += float(info)
        print '33[31mcpu info:  33[0m',
        print 'usr: %.5f%%' % ((usr/total)*100),
        print '     sys: %.5f%%' % ((_sys/total)*100)
    
    def meminfo():
        """
        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, 0
        for info in mem:
            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 - cached
        print "33[31mmeminfo:  33[0m",
        print "total: %.2f GB" % (total/1024/1024),
        print "     used: %.5f%%" % (used/total)
    
    def netinfo():
        """
        get real-time bandwidth
        """
        f = open('/proc/net/dev','r')
        net = f.readlines()
        f.close()
    
        net_item = []
        for info in net:
            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()
                break
        recv_2 = float(_net_item[1])
        send_2 = float(_net_item[9])
    
        #print "recv_2:%s " % recv_2
        #print "send_2:%s " % send_2
        print "33[31m network info:  33[0m"
        print "received: %.3f Kb/s" % (recv_2/1024 - recv/1024)
        print "transmit: %.3f kb/s" % (send_2/1024 - send/1024)
    
    def loadavg():
        pass
    
    def disk():
        pass
    
    if __name__ == '__main__':
        while True:
            try:
                os.system('clear')
                cpuinfo()
                print "=============================================="
                meminfo()
                print "##############################################"
                netinfo()
                time.sleep(5)
            except KeyboardInterrupt, e:  # 这里也可以用信号函数来处理
                print ''
                print "BYE-BYE"
                sys.exit(0)
  • 相关阅读:
    010-spring事务管理
    009-事务管理
    008-ThreadLocal
    Bmob用户管理操作
    Textview下划线注册用户跳转实现
    Android中多个调用Activity的问题
    解决android:theme="@android:style/Theme.NoDisplay" 加入这句话后程序不能运行
    友盟自动更新
    友盟消息推送和更新XML配置
    Android 云服务器的搭建和友盟APP自动更新功能的实现
  • 原文地址:https://www.cnblogs.com/webber1992/p/6165591.html
Copyright © 2011-2022 走看看