Python writes a monitor script similar to top

Source: Internet
Author: User

Recently the boss presented a need, the project needs are roughly as follows:

1, using Raspberry Pi as a gateway, the bottom of a plurality of ZigBee sensor nodes, the gateway to the ZigBee sensor node collected information through the serial port to receive the summary, and sent to the upper HTTP Server;
2, to have the data of the reverse control channel, that is, the gateway and the server to maintain a long connection, using WebSocket implementation, in order to achieve the ZigBee sensor node to send control commands to achieve the remote configuration of ZigBee node operation;
3, the Raspberry Pi gateway itself to interact with the upper server, the upper server can see the gateway real-time CPU, memory and network upstream and downstream bandwidth, and so on;

The first two requirements in the previous period of time has been basically realized, and so on after the time to improve in the collation, today recorded a third of the implementation process.

Feel the third demand is similar to the current company to use the monitoring system of a small bottom-level implementation, because a few days ago bored just took a zabbix environment to play, feel the boss's needs in the front-end seems to resemble the Zabbix server on the kind of presentation form, But with Zabbix really feel not flexible, in fact, I also do not understand, can only achieve a similar to the top tool of the Monitoring script bar, first real-time CPU, memory, network traffic and other information in the local display, waiting for follow-up and server side of the friend, the code is as follows:

#!/usr/bin/env python#-*-coding:utf-8-*-##############################__author__ = ' Webber ' ##create at 2016/12/12 ##############################ImportOSImportSYSImport Timedefcpuinfo ():"""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:", CPUCPU = Cpu.split (" ") Total=0 usr= Float (cpu[2])#user-state CPU usage_sys = float (cpu[4])#CPU usage in kernel State     forInfoinchCPU: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-buffer S-cached"""F= Open ('/proc/meminfo','R') Mem=f.readlines () f.close ( )#print "Meminfo", MemTotal, free, buffers, cached =0, 0, 0, 0 forInfoinchMem:mem_item=Info.lower (). Split ()#Print Mem_item        ifMem_item[0] = ='memtotal:': Total= Float (mem_item[1])        ifMem_item[0] = ='Memfree:': Free= Float (mem_item[1])        ifMem_item[0] = ='buffers:': Buffers= Float (mem_item[1])        ifMem_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= []     forInfoinchNet:ifInfo.strip (). StartsWith ("eth0"): Net_item=Info.strip (). Split () Break    #Print Net_itemrecv = Float (net_item[1]) Send= Float (net_item[9])    #print "recv:%s"% recv    #print "send:%s"% sendTime.sleep (1) F2= Open ('/proc/net/dev','R') _net=f2.readlines () f2.close () _net_item= []     forInfoinch_net:ifInfo.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 ():Passdefdisk ():Passif __name__=='__main__':     whileTrue:Try: Os.system ('Clear') Cpuinfo ()Print "=============================================="Meminfo ()Print "##############################################"NetInfo () time.sleep (5)        exceptKeyboardinterrupt, E:#This can also be handled with a signal function.            Print "'            Print "Bye-bye"sys.exit (0)

Python writes a monitor script similar to top

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.