A simple monitoring system written by Python

Source: Internet
Author: User
There are many open-source monitoring systems on the market: Cacti, Nagios, Zabbix. Don't feel like I need to, why not do it yourself

Two hours with Python hand-off a simple monitoring system, to share with you, I hope to be able to inspire you

First Database Build table

Create a database "Falcon" with the following statement:

CREATE TABLE ' stat ' (' id ' int (one) unsigned not NULL auto_increment, ' host ' varchar () DEFAULT NULL, ' mem_free ' int (11) Default NULL, ' Mem_usage ' int (one) default null, ' Mem_total ' int (one) default null, ' LOAD_AVG ' varchar (+) default NULL, ' t IME ' bigint (one) default NULL, PRIMARY key (' ID '), key ' host ' (' Host ' (255))) Engine=innodb auto_increment=0 default CHARSET =utf8;

First we design a Web service that implements the following functions:

1. Complete the Monitoring page display
2. Accept post-submitted data
3. Provide JSON data get interface

The directory structure is as follows:

Web├──flask_web.py└──templates└──mon.html[/code]flask_web.py[code]import mysqldb as Mysqlimport jsonfrom flask Impor T Flask, request, Render_templateapp = Flask (__name__) db = Mysql.connect (user= "reboot", passwd= "reboot123", \ db= "Falco n ", charset=" UTF8 ") Db.autocommit (True) c = db.cursor () @app. Route ("/", methods=[" GET "," POST "]) def hello (): sql =" "if re Quest.method = = "POST": data = Request.json Try:sql = "INSERT into ' stat ' (' Host ', ' Mem_free ', ' mem_usage ', ' mem_ Total ', ' load_avg ', ' time ') VALUES ('%s ', '%d ', '%d ', '%d ', '%s ', '%d ') "% (data[' Host '], data[' Memfree '], data[' memusage ') , data[' Memtotal '], data[' loadavg '], int (data[' time '))) ret = c.execute (sql) except MySQL. Integrityerror:pass return "OK" Else:return render_template ("mon.html") @app. Route ("/data", methods=["GET"]) d EF GetData (): C.execute ("Select ' Time ', ' mem_usage ' from ' stat '") ones = [[i[0]*1000, i[1]] for i in C.fetchall ()] Retur N "%s" (%s); "% (Request.args.get (' callback '), JSON.DUmps (ones)) if __name__ = = "__main__": App.run (host= "0.0.0.0", port=8888, Debug=true) 

This template page is an example of the Highstock I copied, mon.html

For the sake of simplicity, we only show mem_usage information on the page.

Jb51.net      
 
      Highstock Example                  

The Web presentation page is complete and running:

Python flask_web.py listening on port 8888

We need to make an agent to collect the data and upload the database

moniitems.py

#!/usr/bin/env pythonimport inspectimport timeimport urllib, urllib2import jsonimport socketclass mon:def __init__ (self ): Self.data = {} def getTime (self): return str (int. (Time.time ()) + 8 * 3600) def gethost (self): return SOCKET.G      Ethostname () def getloadavg (self): with open ('/proc/loadavg ') as Load_open:a = Load_open.read (). Split () [: 3] Return ', '. Join (a) def getmemtotal (self): with open ('/proc/meminfo ') as mem_open:a = Int (Mem_open.readline (). Split () [1]) return a/1024 def getmemusage (self, nobuffercache=true): If Nobuffercache:with open ('/proc/        Meminfo ') as Mem_open:t = Int (Mem_open.readline (). Split () [1]) F = Int (Mem_open.readline (). Split () [1]) B = Int (Mem_open.readline (). Split () [1]) C = Int (Mem_open.readline (). Split () [1]) return (T-F-B-C)/1024 E Lse:with open ('/proc/meminfo ') as mem_open:a = Int (Mem_open.readline (). Split () [1])-Int (Mem_open.readline () . Split () [1]) return a/1024 def getmemfree (self, nobuffercache=true): If Nobuffercache:with open ('/proc/meminfo ') as Mem_open: T = Int (Mem_open.readline (). Split () [1]) F = Int (Mem_open.readline (). Split () [1]) B = Int (mem_open.read Line (). Split () [1]) C = Int (Mem_open.readline (). Split () [1]) return (f+b+c)/1024 Else:with open ('/pro    C/meminfo ') as Mem_open:mem_open.readline () a = Int (Mem_open.readline (). Split () [1]) return a/1024  def runallget (self): #自动获取mon类里的所有getXXX方法, with the return value of XXX as key,getxxx () as value, constructs the dictionary for fun in Inspect.getmembers (self, Predicate=inspect.ismethod): if fun[0][:3] = = ' Get ': self.data[fun[0][3:]] = fun[1] () return Self.dataif _ _name__ = = "__main__": While true:m = Mon () data = M.runallget () print data req = Urllib2. Request ("http://jb51.net:8888", Json.dumps (data), {' Content-type ': ' Application/json '}) F = Urllib2.urlopen (req) Res Ponse = F.read () print response f.clOSE () time.sleep nohup python moniitems.py >/dev/null 2>&1 & Running Up 

Visit http://jb51.net:8888 to see our monitoring data: the following

  • 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.