用Python写一个简单的监控系统

同样是先搭环境

第0步:环境

yum install gcc gcc-c++ libgcc libstdc++ libgcc-devel libstdc++-devel zlib zlib-devel openssl openssl-devel pcre pcre-devel


tar -xvzf Python-3.5.1.tgz
./configure --prefix=/opt/python3
make
make install

pip install virtualenv

mkdir /opt/myproject
cd /opt/myproject
/opt/python3/bin/virtualenv ooo
. ooo/bin/activate


pip install flask
pip install pymysql

第1步:数据库就是建一张表stat

CREATE TABLE `stat` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `host` varchar(256) DEFAULT NULL,
  `mem_free` int(11) DEFAULT NULL,
  `mem_usage` int(11) DEFAULT NULL,
  `mem_total` int(11) DEFAULT NULL,
  `load_avg` varchar(128) DEFAULT NULL,
  `time` bigint(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `host` (`host`(255))
) ENGINE=MyISAM AUTO_INCREMENT=8 DEFAULT CHARSET=utf8

第2步:设计

首先我们设计一个web服务,实现如下功能:

完成监控页面展示
接受POST提交上来的数据
提供json数据GET接口
目录结构如下:

web
├── flask_web.py
└── templates
    └── mon.html

flask_web.py

#!/bin/env python
# coding:utf-8

import pymysql
import json
from flask import Flask, request, render_template
app = Flask(__name__)

con = pymysql.connect(host="localhost", port=3306, user="root", passwd="root__", database= "meminfo", charset="utf8")
con.autocommit(True)
cur = con.cursor()

@app.route("/", methods=["GET", "POST"])
def hello():
    sql = ""
    if request.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 = cur.execute(sql)
        except pymysql.IntegrityError:
            pass
        return "OK"
    else:
        return render_template("mon.html")

@app.route("/data", methods=["GET"])
def getdata():
    cur.execute("SELECT `time`,`mem_usage` FROM `stat`")
    ones = [[i[0]*1000, i[1]] for i in cur.fetchall()]
    return "%s(%s);" % (request.args.get('callback'), json.dumps(ones))
    

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000, debug=True)

mon.html

<!DOCTYPE HTML>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>Highstock Example</title>

        <script type="text/javascript" src="http://cdn.hcharts.cn/jquery/jquery-1.8.3.min.js"></script>
        <style type="text/css">
${demo.css}
        </style>
        <script type="text/javascript">
$(function () {
    $.getJSON('/data?callback=?', function (data) {

        // Create the chart
        $('#container').highcharts('StockChart', {

            rangeSelector: {
                inputEnabled: $('#container').width() > 480,
                selected: 1
            },

            title: {
                text: '51Reboot.com'
            },

            series: [{
                name: '51Reboot.com',
                data: data,
                type: 'spline',
                tooltip: {
                    valueDecimals: 2
                }
            }]
        });
    });
});
        </script>
    </head>
    <body>
<script src="http://cdnjs.cloudflare.com/ajax/libs/highstock/2.0.4/highstock.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>


<div id="container" style="height: 400px"></div>
    </body>
</html>

moniTem.py

#!/bin/env python
# coding:utf-8
import inspect
import time
import urllib, urllib2
import json
import socket

class mon:
    def __init__(self):
        self.data = {}

    def getTime(self):
        return str(int(time.time()) + 8 * 3600)

    def getHost(self):
        return socket.gethostname()

    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
        else:
            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.readline().split()[1])
                C = int(mem_open.readline().split()[1])
                return (F+B+C)/1024
        else:
            with open('/proc/meminfo') as mem_open:
                mem_open.readline()
                a = int(mem_open.readline().split()[1])
                return a / 1024
    
    def runAllGet(self):
        #自动获取mon类里的所有getXXX方法,用XXX作为key,getXXX()的返回值作为value,构造字典
        for fun in inspect.getmembers(self, predicate=inspect.ismethod):
            if fun[0][:3] == 'get':
                self.data[fun[0][3:]] = fun[1]()
        return self.data

if __name__ == "__main__":
    while True:
        m = mon()
        data = m.runAllGet()
        print data
        req = urllib2.Request("http://192.168.1.58:5000", json.dumps(data), {'Content-Type': 'application/json'})
        f = urllib2.urlopen(req)
        response = f.read()
        print response
        f.close()
        time.sleep(60)

然后运行,结果和上一篇差不多。

你可能感兴趣的:(用Python写一个简单的监控系统)