1、需求:
(1)在局域网内计算机运行python程序,检测每台计算机的的cpu、内存占用情况
(2)检测到的内容上传到mongodb
(3)管理员可以在网页上查到相关计算机运行指标的变化
2、环境准备
(1)安装python3.72
(2)安装flask、psutil、pymongo
(3)安装mongodb4.0
3、代码实现
3.1在mongdb建立数据表
建立数据库:use monitor
建立数据集:db.createCollection("monitor",{'host':'192.168.1.1'},{'boot_start':''},{'boot_start':''},{'cpu_usage':'192.168.1.1'},{'ram':''},{'ram_percent':''},{'recordDate':''},)
3.2python功能开发
monitor.py--------------------监控信息写入数据库 monitor.bat------------------windows运行脚本,在自动运行中加入,每15分钟运行一次 monitorservice.py------------将数据写成jsonobject格式传给前台 eharts1.html------------------echars、ajax实现自动绘图,自动生成多条曲线 具体代码如下: monitor.py组件监控计算机状态,将cpu占用率写入数据库
#Author:zhangguoqing
#目标:调取监控数据并保存到数据库
#引用类库
import socket
import psutil
import time
import pymongo
import threading
import sched
from random import randint
#连接数据库
DBSerSetPara = {
"ip":'localhost',
"port":27017,
"DbName":"monitor",
"SetName":"baseInfo"
}
conn = pymongo.MongoClient(DBSerSetPara["ip"],DBSerSetPara["port"])
db = conn.monitor #连接数据库
tblmonitor = db.tblmonitor #连接数据集合
DictMonitor = {}
#获取监控信息
def funMonitor():
#获得主机名称
host_name = socket.gethostname()
#获得主机ip
host_ip = socket.gethostbyname_ex(host_name)[2][0]
# 获得启动时间
boot_start = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(psutil.boot_time()))
# 主线程延迟0.5
time.sleep(0.5)
# cpu_usage
cpu_usage = psutil.cpu_percent()
# RAM
ram = int(psutil.virtual_memory().total / (1027 * 1024))
# RAM占用比例
ram_percent = psutil.virtual_memory().percent
#如下代码为数据插入字典
IPAddressEndNumber = str(randint(1, 10)) #为了单机展示效果好一些,这里生成随机的多个IP地址,
DictMonitor['host'] = '192.168.1.' + IPAddressEndNumber
DictMonitor['boot_start'] = boot_start
DictMonitor['cpu_usage'] = cpu_usage
DictMonitor['ram'] = ram
DictMonitor['ram_percent'] = ram_percent
DictMonitor['recordDate'] = str(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()))
result = tblmonitor.insert_one(DictMonitor)
print(result.inserted_id)
#每两秒钟记录一下系统的状态
def RegularTimeRun():
timer = threading.Timer(2,funMonitor)
timer.start()
#主程序
if __name__ == '__main__':
funMonitor()
# RegularTimeRun()
monitorservice.py:将数据库中收集到的信息,写成json格式发给前台echarts
#Author:zhangguoqing
# 0 导入mongo 插件
from pymongo import MongoClient
from random import randint #随机函数
import time
from bson import Code
import json
# 1 建立数据库连接
#建立字典类型参数库
DBSerSetPara = {
"ip":'localhost',
"port":27017,
"DbName":"monitor",
"SetName":"baseInfo"
}
conn = MongoClient(DBSerSetPara["ip"],DBSerSetPara["port"])
db = conn.monitor #连接数据库
tblmonitor = db.tblmonitor #连接数据集合
DictMonitor = {}
#给echarts提供数据
#一是柱状图,x轴ip地址,y轴为每个主机占有率前五名的数据
def funSelectAll():
# 使用分组函数,数据库中筛选出所有IP地址,保存到SeriesNameList[]列表中
func = '''
function(obj,prev)
{
prev.count++;
}
'''
resultGroup = tblmonitor.group(key={'host': 1}, condition={}, initial={"count": 0}, reduce=func)
SeriesNameList = []
for item in resultGroup:
SeriesNameList.append(item['host'])
#以SeriesNameList即IP地址为外循环,每次以Ip为查询条件,在数据库中查出cpu_usage写到SeriesDataList[]中
SeriesDataList = []
SeriesJson = {}
SeriesJsonList = []
for item in SeriesNameList:
ResultSort = tblmonitor.find({'host': item}, {"_id": 0, "cpu_usage": 1}).sort([('cpu_usage', 1)]).limit(10)
for ResultSortItem in ResultSort:
SeriesDataList.append(ResultSortItem['cpu_usage'])
SeriesJson["name"] = item
SeriesJson["type"] = "line"
SeriesJson["data"] = SeriesDataList.copy()
SeriesJsonList.append(SeriesJson.copy())
SeriesDataList.clear()
print(json.dumps(SeriesJsonList))
return json.dumps(SeriesJsonList)
#返回对应的json格式
#主程序
if __name__ == '__main__':
funSelectAll()
3.2用flask搭建web服务器
#Author:zhangguoqing
#使用flask作为web服务
#flask包含两个目录templates放置网页,static放置css及js等引用文件
#此文件为导航文件
import flask
from pymongo import MongoClient
from monitorservice import funSelectAll
# from mariadb.db0 import funSelectAll
app = flask.Flask(__name__)
@app.route('/',methods=['GET','POST'])
def funIndex():
print('index')
return flask.render_template('index.html')
@app.route('/echarts1',methods=['GET','POST'])
def funEcharts1():
print('echarts1')
return flask.render_template('echarts1.html')
@app.route('/funSelectAll',methods=['GET','POST'])
def funSelectAll0():
print('asdfdsfs')
return funSelectAll()
if __name__ == '__main__':
app.run(host = "127.0.0.1",port = "22222",debug = True)
3.3eharts1.html echars、ajax实现自动绘图,自动生成多条曲线
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="{{url_for('static',filename='echarts.min.js')}}"></script>
<script src="{{url_for('static',filename='jquery.min.js')}}"></script>
<title>monitor charts</title>
</head>
<body>
<!-- 为ECharts准备一个具备大小(宽高)的Dom -->
<div id="main" style="width: 1200px;height:400px;"></div>
<div id="main1" style="width: 600px;height:400px;"></div>
<script type="text/javascript">
// 基于准备好的dom,初始化echarts实例
var CPU_usage_Chart = echarts.init(document.getElementById('main'));
// 指定图表的配置项和数据
var CPU_usage_option = {
title: {
text: 'CPU使用率变化图'
},
tooltip: {
trigger: 'axis'
},
legend: {
data:['邮件营销','联盟广告','视频广告','直接访问','搜索引擎']
},
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true
},
toolbox: {
feature: {
saveAsImage: {}
}
},
xAxis: {
type: 'category',
boundaryGap: false
},
yAxis: {
type: 'value'
},
series: [
{
name:"邮件营销",
type:'line',
stack: '总量',
data:[120, 132, 101, 134, 90, 230, 210]
},
{
name:'联盟广告',
type:'line',
stack: '总量',
data:[220, 182, 191, 234, 290, 330, 310]
},
{
name:'视频广告',
type:'line',
stack: '总量',
data:[150, 232, 201, 154, 190, 330, 410]
},
{
name:'直接访问',
type:'line',
stack: '总量',
data:[320, 332, 301, 334, 390, 330, 320]
},
{
name:'搜索引擎',
type:'line',
stack: '总量',
data:[820, 932, 901, 934, 1290, 1330, 1320]
}
]
};
// 使用刚指定的配置项和数据显示图表。
//CPU_usage_Chart.setOption(option);
//*******************************************ajax start********************************
var series1 = []
$(document).ready(function () {
setInterval(funSelectAllCpu,5000);
function funSelectAllCpu(){
$.ajax({
url:'/funSelectAll',
type:'get',
dataType:'json',
//timeOut:10000,
success:function (msg) {
//option
for (var i = 0; i < msg.length ; i++) {
CPU_usage_option.legend.data[i] = msg[i].name.toString()
}
CPU_usage_option.series = msg
//alert(JSON.stringify(CPU_usage_option))
CPU_usage_Chart.setOption(CPU_usage_option);
},
error:function () {
}
});
}
// window.setInterval("funSelectAllCpu()",3000);
//平均每隔5秒进行一次请求
});
//ajax stop
</script>
</body>
</html>
实现效果如下: