欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python寫的一個(gè)簡單監(jiān)控系統(tǒng)

 更新時(shí)間:2015年06月19日 10:25:27   投稿:junjie  
這篇文章主要介紹了Python寫的一個(gè)簡單監(jiān)控系統(tǒng),本文講解了詳細(xì)的編碼步驟,并給給出相應(yīng)的實(shí)現(xiàn)代碼,需要的朋友可以參考下

市面上有很多開源的監(jiān)控系統(tǒng):Cacti、nagios、zabbix。感覺都不符合我的需求,為什么不自己做一個(gè)呢

用Python兩個(gè)小時(shí)徒手?jǐn)]了一個(gè)簡易的監(jiān)控系統(tǒng),給大家分享一下,希望能對大家有所啟發(fā)

首先數(shù)據(jù)庫建表

建立一個(gè)數(shù)據(jù)庫“falcon”,建表語句如下:

CREATE TABLE `stat` (
 `id` int(11) unsigned 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=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;

首先我們設(shè)計(jì)一個(gè)web服務(wù),實(shí)現(xiàn)如下功能:

1.完成監(jiān)控頁面展示
2.接受POST提交上來的數(shù)據(jù)
3.提供json數(shù)據(jù)GET接口

目錄結(jié)構(gòu)如下:

web
├── flask_web.py
└── templates
  └── mon.html
[/code]
flask_web.py
[code]
import MySQLdb as mysql
import json
from flask import Flask, request, render_template
app = Flask(__name__)
db = mysql.connect(user="reboot", passwd="reboot123", \
    db="falcon", charset="utf8")
db.autocommit(True)
c = db.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 = c.execute(sql)
    except mysql.IntegrityError:
      pass
    return "OK"
  else:
    return render_template("mon.html")

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

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

這個(gè)template頁面是我抄的highstock的示例,mon.html

簡單起見我們只展示mem_usage信息到頁面上

<title>jb51.net</title>
<!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://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.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: 'jb51.net'
      },

      series: [{
        name: 'jb51.net',
        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>

web展示頁面完成了,運(yùn)行起來:

Python flask_web.py 監(jiān)聽在8888端口上

我們需要做一個(gè)agent來采集數(shù)據(jù),并上傳數(shù)據(jù)庫

moniItems.py

#!/usr/bin/env python
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):
    #自動(dòng)獲取mon類里的所有g(shù)etXXX方法,用XXX作為key,getXXX()的返回值作為value,構(gòu)造字典
    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://jb51.net:8888", json.dumps(data), {'Content-Type': 'application/json'})
    f = urllib2.urlopen(req)
    response = f.read()
    print response
    f.close()
    time.sleep(60)


nohup python moniItems.py >/dev/null 2>&1 & 運(yùn)行起來

訪問 http://jb51.net:8888 就可以看到我們的監(jiān)控?cái)?shù)據(jù)了:效果圖如下


相關(guān)文章

  • Python?Pytorch學(xué)習(xí)之圖像檢索實(shí)踐

    Python?Pytorch學(xué)習(xí)之圖像檢索實(shí)踐

    隨著電子商務(wù)和在線網(wǎng)站的出現(xiàn),圖像檢索在我們的日常生活中的應(yīng)用一直在增加。圖像檢索的基本本質(zhì)是根據(jù)查詢圖像的特征從集合或數(shù)據(jù)庫中查找圖像。本文將利用Pytorch實(shí)現(xiàn)圖像檢索,需要的可以參考一下
    2022-04-04
  • PyQt信號(hào)和槽機(jī)制的具體使用

    PyQt信號(hào)和槽機(jī)制的具體使用

    信號(hào)和槽機(jī)制是一種通信機(jī)制,在PyQt中,信號(hào)是一種特殊的函數(shù),它可以傳遞任何類型的數(shù)據(jù),而槽則是一種接收信號(hào)的函數(shù),本文就介紹了PyQt信號(hào)和槽機(jī)制的具體使用,感興趣的可以了解一下
    2023-08-08
  • Python hashlib加密模塊常用方法解析

    Python hashlib加密模塊常用方法解析

    這篇文章主要介紹了Python hashlib加密模塊常用方法解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-12-12
  • 利用Python批量處理多個(gè)txt文本的示例代碼

    利用Python批量處理多個(gè)txt文本的示例代碼

    這篇文章主要給大家介紹了關(guān)于如何利用Python批量處理多個(gè)txt文本的方法,文中通過實(shí)例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下
    2023-10-10
  • Python實(shí)現(xiàn)簡單多線程任務(wù)隊(duì)列

    Python實(shí)現(xiàn)簡單多線程任務(wù)隊(duì)列

    本文給大家介紹的是使用很簡單的代碼實(shí)現(xiàn)的多線程任務(wù)隊(duì)列,給大家一個(gè)思路,希望對大家學(xué)習(xí)python能夠有所幫助
    2016-02-02
  • Python3中條件控制、循環(huán)與函數(shù)的簡易教程

    Python3中條件控制、循環(huán)與函數(shù)的簡易教程

    這篇文章主要給大家介紹了關(guān)于Python3中條件控制、循環(huán)與函數(shù)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。
    2017-11-11
  • python列表去重的二種方法

    python列表去重的二種方法

    這篇文章主要介紹了python列表去重的二種方法,第二種方法無法保持原有順序,需要的朋友可以參考下
    2014-02-02
  • python3爬取數(shù)據(jù)至mysql的方法

    python3爬取數(shù)據(jù)至mysql的方法

    這篇文章主要為大家詳細(xì)介紹了python3爬取數(shù)據(jù)至mysql的方法 ,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-06-06
  • Python編程中NotImplementedError的使用方法

    Python編程中NotImplementedError的使用方法

    下面小編就為大家分享一篇Python編程中NotImplementedError的使用方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-04-04
  • pycharm沒有找到manage?repositories按鈕的解決辦法

    pycharm沒有找到manage?repositories按鈕的解決辦法

    這篇文章主要給大家介紹了關(guān)于pycharm沒有找到manage?repositories按鈕的解決辦法,pycharm是用來寫python的可視化代碼軟件,文中通過圖文介紹的非常詳細(xì),需要的朋友可以參考下
    2023-07-07

最新評論