python 寫一個類似於top的監控指令碼

來源:互聯網
上載者:User

標籤:串連   except   樹莓派   c/s   記錄   指令碼   反向   並且   size   

最近老闆給提出一個需要,項目需求大致如下:

     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 osimport sysimport timedef 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 ‘\033[31mcpu info:  \033[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 "\033[31mmeminfo:  \033[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 "\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)def loadavg():    passdef disk():    passif __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)

 

python 寫一個類似於top的監控指令碼

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.