使用python写一个监控不同机器的使用内存情况并使用flask出图

基于是自己想要扩展前一篇博客的内容所以直接就把代码传上去了能做出的效果是可以像zabbix那样监控多台主机上的使用内存情况;

出来图片结果是:

js代码是从一下地址拉取

https://www.hcharts.cn/demo/highstock/basic-line

我使用的是以下地址的js代码

https://www.hcharts.cn/demo/highstock/compare/dark-unica

 

使用python写一个监控不同机器的使用内存情况并使用flask出图

 

1、 监控多台主机内存并写到各自的数据库里面:

[[email protected] mem_more]# cat save_mem.py
#_*_coding:utf-8_*_
 
import time
import MySQLdb as mysql
import os
 
db1 = mysql.connect(user="root",passwd="redhat",db="mem",host="192.168.5.101")
db1.autocommit(True)
cur1 = db1.cursor()
 
db2 = mysql.connect(user="root",passwd="redhat",db="mem",host="localhost")
db2.autocommit(True)
cur2 = db2.cursor()
 
 
def save_mem1():
       f = os.popen("sshpass -p 'redhat' ssh [email protected]  cat /proc/meminfo")
       total = int(f.readlines()[0].split()[1])
       f = os.popen("sshpass -p 'redhat' ssh [email protected]  cat /proc/meminfo")
       aviable = int(f.readlines()[2].split()[1])
       mem1 = (total-aviable)/1024
       cur1_time = int(time.time())
       sql = 'insert into mem(mem,date) values(%s,%s)' %(mem1,cur1_time)
       cur1.execute(sql)
       print mem1
 
def save_mem2():
       f = open("/proc/meminfo")
       total = int(f.readlines()[0].split()[1])
       f = open("/proc/meminfo")
       aviable = int(f.readlines()[2].split()[1])
       mem2 = (total-aviable)/1024
       cur2_time = int(time.time())
       sql = 'insert into mem(mem,date) values(%s,%s)' %(mem2,cur2_time)
       cur2.execute(sql)
       print mem2
 
while True:
       save_mem1()
       save_mem2()
       time.sleep(1)

 

调用flask模块出图:

[[email protected] mem_more]# cat flask_web.py
#_*_coding:utf-8_*_
from flask import Flask,render_template
import MySQLdb as mysql
import json
 
con1 = mysql.connect(user="root",passwd="redhat",db="mem",host="192.168.5.101")
con1.autocommit(True)
cur1 = con1.cursor()
 
con2 = mysql.connect(user="root",passwd="redhat",db="mem",host="localhost")
con2.autocommit(True)
cur2 = con2.cursor()
 
app = Flask(__name__)
 
last_time1 = 0
last_time2 = 0
@app.route('/')
def index():
#     return "cml test"
       return render_template('index.html')
 
@app.route('/cml/a')
def cml_a():
       global last_time1
       if (last_time1 > 0):
              sql = 'select * from mem where date > %s' %(last_time1/1000)
       else:
              sql = 'select * from mem'
       cur1.execute(sql)
       arr = []
       for i in cur1.fetchall():
#            print i
              arr.append([i[1]*1000,i[0]])
#     return "ok"
       if (len(arr) > 0):
              last_time1 = arr[-1][0]
       return json.dumps(arr)
 
@app.route('/cml/b')
def cml_b():
       global last_time2
       if (last_time2 > 0):
              sql = 'select * from mem where date > %s' %(last_time2/1000)
       else:
              sql = 'select * from mem'
       cur2.execute(sql)
       arr = []
       for i in cur2.fetchall():
#            print i
              arr.append([i[1]*1000,i[0]])
#     return "ok"
#     print "-----arr:", arr
       if (len(arr) > 0):
              last_time2 = arr[-1][0]
       return json.dumps(arr)
 
if __name__=='__main__':
       app.run(host='0.0.0.0',port=9092,debug=True)

配置网页index.html:

[[email protected] mem_more]# cat templates/index.html
<html>
<head>
        <title> my memory monitor </title>
</head>
 
<body>
<div id="container" style="min-width:400px;height:400px"></div>
 
<script src='/static/jquery.js'></script>
<script src='/static/highstock.js'></script>
<script>
$(function () {
    var seriesOptions = [],
        seriesCounter = 0,
        names = ['a', 'b'],
        // create the chart when all data is loaded
        createChart = function () {
            $('#container').highcharts('StockChart', {
              chart: {
                            events: {
                                   load:function() {
                                          var series = this.series[0]
                                          setInterval(
                                                 // 表示每隔3000ms(参数2),就执行指定的函数(参数1)
                                                 function(){
                                                        $.getJSON('/cml/' + name.toLowerCase(),function(res){
                                                               $.each(res, function(i,v){
                                                                    series.addPoint(v)
                                                               })
                                                        })
                                                 },
                                                 3000)
                                   }            
                            }
                     },
 
 
                rangeSelector: {
                    selected: 4
                },
                yAxis: {
                    labels: {
                        formatter: function () {
                            return (this.value > 0 ? ' + ' : '') + this.value + '%';
                        }
                    },
                    plotLines: [{
                        value: 0,
                        width: 2,
                        color: 'silver'
                    }]
                },
                plotOptions: {
                    series: {
                        compare: 'percent'
                    }
                },
                tooltip: {
                    pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b> ({point.change}%)<br/>',
                    valueDecimals: 2
                },
                series: seriesOptions
            });
        };
    $.each(names, function (i, name) {
        $.getJSON('/cml/' + name.toLowerCase(),    function (cml) {
            seriesOptions[i] = {
                name: name,
                data: cml
            };
            // As we're loading the data asynchronously, we don't know what order it will arrive. So
            // we keep a counter and create the chart when all the data is loaded.
            seriesCounter += 1;
            if (seriesCounter === names.length) {
                createChart();
            }
        });
    });
});
 
</script>
</body>
</html>