按照http://51reboot.com/python36-falcon-mon-video/ 一步步操作实现一个简单的系统监控
我自己安装的是Python 3.5 和博客里面的版本不太一样
而且博主是用于监控Linux系统,我修改了些代码可以检测到Windows的信息
还有个地方是博主用的是Mysql,我也懒得装,我就用Sqlit3。
先把flask环境搭建好
建个数据库
from sqlite3 import dbapi2 as sqlite3
conn = sqlite3.connect('stat')
print("创建数据库成功")
conn.execute("""create table stat(
id integer primary key autoincrement,
host string,
mem_free integer,
mem_usage integer,
mem_total integer,
time integer
);""")
print("数据表创建成功")
建好后别忘了执行一下。
Server 部分基本与51reboot里一样
from sqlite3 import dbapi2 as mysql
import json
from flask import Flask, request, render_template
app = Flask(__name__)
db = mysql.connect("stat",check_same_thread=False)
db.commit()
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,time) VALUES('%s', '%s', '%s', '%s', '%d')" % (data['Host'], data['MemFree'], data['MemUsage'], data['MemTotal'], int(data['Time']))
ret = c.execute(sql)
except mysql.IntegrityError:
print("error")
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)
模板部分就是直接粘过来的
agent部分做了较大修改,引用了wmi来获取windows的信息
import inspect
import time
import json
import socket
import wmi
import os
import win32con
import win32api
import urllib.request
class mon:
def __init__(self):
self.data = {}
def getTime(self):
return str(int(time.time()) + 8 * 3600)
def getHost(self):
return socket.gethostname()
def getMemTotal(self):
c = wmi.WMI()
for sys in c.Win32_OperatingSystem():
return sys.TotalVisibleMemorySize
def getMemUsage(self):
c = wmi.WMI()
for sys in c.Win32_OperatingSystem():
total = sys.TotalVisibleMemorySize
free = sys.FreePhysicalMemory
usage = int(total)-int(free)
#print()
return str(usage)
def getMemFree(self):
c = wmi.WMI()
for sys in c.Win32_OperatingSystem():
return sys.FreePhysicalMemory
def runAllGet(self):
for fun in inspect.getmembers(self,predicate=inspect.ismethod):
#for fun in [getTime,getHost,getMemtotal,getMemUsage,getMemFree]:
#print(fun[:3])
if fun[0][:3] == 'get':
#print(fun[:3])
self.data[fun[0][3:]] = fun[1]()
#print(self.data)
return self.data
if __name__ == "__main__":
while True:
m = mon()
values = m.runAllGet()
print(values)
#data = urllib.parse.urlencode(values).encode('utf-8')
#print(data)
data = json.dumps(values)
data = bytes(data,'utf-8') #改变数据类型为bytes,不然在urlopen时无法传递数据
#print(data)
req = urllib.request.Request("http://127.0.0.1:8888",data,{'Content-Type': 'application/json'})
print(req)
try:
f = urllib.request.urlopen(req)
except urllib.error.HTTPError as e: 这个抛出异常的代码很有用,我弄了2天一直卡在这,总提示500的错误,查了很多资料后来看到这个加上去后立马找到了错误的原因。
print(e.code)
print(e.read().decode())
#f = urllib.parse.urlencode(b'req')
response=f.read()
print(response)
f.close()
time.sleep(60)
51reboot博主用了2小时就鲁出来了,我照着做还用了2天可见差距。
虽然代码不美观,有些地方的重复定义也可能导致系统性能下降,但程序运行起来了,心情瞬间就好了。