Python搭建一個(gè)系統(tǒng)信息實(shí)時(shí)監(jiān)控?cái)?shù)據(jù)可視化大屏

本文分享使用python搭建服務(wù)器應(yīng)用的監(jiān)控系統(tǒng)面板,主要流程如下:
1、數(shù)據(jù)庫中創(chuàng)建數(shù)據(jù)表
2、建立數(shù)據(jù)庫連接
實(shí)時(shí)數(shù)據(jù)插入數(shù)據(jù)表,實(shí)時(shí)查詢更新面板數(shù)據(jù)準(zhǔn)備
3、監(jiān)控中心大屏制作
具體步驟:
1、創(chuàng)建監(jiān)測(cè)指標(biāo)數(shù)據(jù)表字段
這里為了方便將系統(tǒng)信息監(jiān)控的CPU信息、內(nèi)存信息、磁盤信息放在一張表中。
實(shí)際上可以將CPU和磁盤信息監(jiān)控指標(biāo)分表設(shè)置,兩者對(duì)時(shí)間粒度要求是不一樣的,減少不需要的資源消耗。后期專門寫一篇來聊聊如何搭建數(shù)據(jù)指標(biāo)體系。
import pymysql
db = pymysql.connect(user="root", passwd="root", db="mydb", host="127.0.0.1")
cur = db.cursor()
# from sqlalchemy import create_engine
# engine = create_engine(
# "mysql+pymysql://root:[email protected]:3306/mydb?charset=utf8")
# print(engine)
# 創(chuàng)建數(shù)據(jù)表--系統(tǒng)信息監(jiān)控
sql="""CREATE TABLE IF NOT EXISTS system_info(
ID int(8) not null auto_increment COMMENT '序號(hào)',
TIME datetime not null COMMENT '記錄時(shí)間',
mem_free VARCHAR (100) NOT NULL COMMENT '可用內(nèi)存',
mem_total VARCHAR (100) NOT NULL COMMENT '總內(nèi)存',
mem_percent VARCHAR (100) NOT NULL COMMENT '內(nèi)存百分比',
mem_used VARCHAR (100) NOT NULL COMMENT '占用內(nèi)存',
cpu VARCHAR (100) COMMENT 'CPU占比',
disk1 VARCHAR (100) COMMENT 'C盤使用占比',
disk2 VARCHAR (100) COMMENT 'D盤使用占比',
disk3 VARCHAR (100) COMMENT 'E盤使用占比',
disk4 VARCHAR (100) COMMENT 'F盤使用占比',
disk5 VARCHAR (100) COMMENT 'G盤使用占比',
primary key(ID)
) ENGINE = INNODB DEFAULT CHARSET = utf8 COMMENT = '系統(tǒng)信息監(jiān)控';
"""
cur.execute(sql)
cur.close()

2、建立數(shù)據(jù)庫連接
定時(shí)獲取主機(jī)的一些內(nèi)存、CPU、磁盤的信息,將獲取的信息存儲(chǔ)到數(shù)據(jù)庫;這里利用輕量級(jí)定時(shí)模塊schedule。
import psutil
import time
import pymysql
from datetime import datetime
import schedule
db = pymysql.connect(user="root", passwd="root", db="mydb", host="127.0.0.1")
db.autocommit(True)
cur = db.cursor()
def Get_sys_info():
# cpu信息
cpu = str(psutil.cpu_percent(interval=1)) + '%'
# cpu = psutil.cpu_percent(interval=1, percpu=True)
# 內(nèi)存信息
mem = psutil.virtual_memory()
mem_total = round(mem.total / 1024 / 1024 / 1024, 0)
mem_free = round(mem.free / 1024 / 1024 / 1024)
mem_percent = str(mem.percent) + '%'
mem_used = round(mem.used / 1024 / 1024 / 1024)
# 磁盤信息(磁盤空間使用占比)
disk1 = str(psutil.disk_usage('C:/').percent) + '%'
disk2 = str(psutil.disk_usage('D:/').percent) + '%'
disk3 = str(psutil.disk_usage('E:/').percent) + '%'
disk4 = str(psutil.disk_usage('F:/').percent) + '%'
disk5 = str(psutil.disk_usage('G:/').percent) + '%'
return mem_free,mem_total,mem_percent,mem_used,cpu,disk1,disk2,disk3,disk4,disk5
if __name__ == "__main__":
def job():
mem_free, mem_total, mem_percent, mem_used, cpu, disk1, disk2, disk3, disk4, disk5 = Get_sys_info()
now_time = datetime.now()
list1 = [now_time, mem_free, mem_total, mem_percent, mem_used, cpu, disk1, disk2, disk3, disk4, disk5]
tuple_list = tuple([str(i) for i in list1])
print(tuple_list)
sql = """insert into system_info(TIME,mem_free,mem_total,mem_percent,mem_used,cpu,disk1,disk2,disk3,disk4,disk5) value (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"""
cur.execute(sql, tuple_list)
try:
schedule.every().minute.at(":00").do(job)
except Exception as e:
print('錯(cuò)誤: %s'% e)
while True:
schedule.run_pending()
time.sleep(1)
服務(wù)啟動(dòng)后,每分鐘向數(shù)據(jù)庫插入一次數(shù)據(jù)記錄。這里有個(gè)小問題,插入時(shí)間點(diǎn)并沒有從設(shè)置的:00開始,后面再優(yōu)化這個(gè)細(xì)節(jié)。

3、監(jiān)控中心大屏
從數(shù)據(jù)庫獲取數(shù)據(jù)如服務(wù)器的內(nèi)存、CPU信息等,通過Pyecharts可視化制作圖表并布局看板。通過以下流程生成一個(gè)粗略的大屏布局,由7個(gè)部分組成,按順序排列。
import pymysql
from pyecharts.charts import Line
from pyecharts import options as opts
from pyecharts.charts import Bar, Pie, Page
from pyecharts.globals import ThemeType
db = pymysql.connect(user="root", passwd="root", db="mydb", host="127.0.0.1")
cur1 = db.cursor()
cur2 = db.cursor()
cur3 = db.cursor()
SQL1="""SELECT TIME,cpu,mem_percent FROM system_info WHERE TIME > DATE_SUB(NOW(), INTERVAL 60 MINUTE)""" #查詢最近1h內(nèi)數(shù)據(jù)展示
SQL2 = 'select disk1,disk2,disk3,disk4,disk5 from system_info order by TIME desc limit 1'
SQL3 = 'select mem_free,mem_total,mem_percent,mem_used from system_info order by TIME desc limit 1'
cur1.execute(SQL1)
cur2.execute(SQL2)
cur3.execute(SQL3)
cpu_data = cur1.fetchall()
disk_data = cur2.fetchall()
mem_data = cur3.fetchall()
all_time = []
all_cpu = []
all_mem_percent = []
for time_cpu in cpu_data:
TIME=time_cpu[0]
cpu0=time_cpu[1].split('%')
cpu_num = eval(cpu0[0])
mem0=time_cpu[2].split('%')
mem_percent = eval(mem0[0])
all_cpu.append(cpu_num)
all_time.append(TIME)
all_mem_percent.append(mem_percent)
disk_list = list(disk_data[0])
disk_percent=[eval(x.split("%")[0]) for x in disk_list]
def tab0(name, color): # 標(biāo)題
c = (Pie().
set_global_opts(
title_opts=opts.TitleOpts(title=name, pos_left='center', pos_top='center',
title_textstyle_opts=opts.TextStyleOpts(color=color, font_size=20))))
return c
def tab1(name, color): # 標(biāo)題
c = (Pie().
set_global_opts(
title_opts=opts.TitleOpts(title=name, pos_left='center', pos_top='center',
title_textstyle_opts=opts.TextStyleOpts(color=color, font_size=30))))
return c
def tab2(name, color):
c = (Pie().
set_global_opts(
title_opts=opts.TitleOpts(title=name, pos_left='center', pos_top='center',
title_textstyle_opts=opts.TextStyleOpts(color=color, font_size=25))))
return c
def line(all_time, all_cpu):
line = (
Line()
.add_xaxis(all_time)
.add_yaxis("CPU_info:%", all_cpu)
.set_global_opts(title_opts=opts.TitleOpts(title="CPU_info"))
)
line.render()
return line
def line1(all_time, all_mem_percent):
line = (
Line()
.add_xaxis(all_time)
.add_yaxis("Mem_percent:%",all_mem_percent)
.set_global_opts(title_opts=opts.TitleOpts(title="內(nèi)存使用占比"))
)
line.render()
return line
def bar(disk_percent):
bar =(Bar(init_opts=opts.InitOpts(theme=ThemeType.CHALK)) #在這里輸入啊,設(shè)置繪圖主題為CHALK
.add_xaxis(["C盤","D盤","E盤","F盤","G盤"])
.add_yaxis("磁盤使用占比:%",disk_percent))
bar.render()
return bar
def pie_base():
c = (
Pie()
.add("", [list(z) for z in zip(['mem_free', 'mem_used'],
[mem_data[0][0],mem_data[0][3]])])
.set_global_opts(title_opts=opts.TitleOpts(title="內(nèi)存使用占比"))
.set_series_opts(label_opts=opts.LabelOpts(formatter=": {c}"))
)
return c
#將上面圖拼接到網(wǎng)頁上
page = Page()
page.add(
tab0("Python數(shù)據(jù)分析實(shí)例", "#2CB34A"),
line(all_time,all_cpu),
tab1("系統(tǒng)信息監(jiān)控?cái)?shù)據(jù)可視化大屏", "#2CB34A"),
tab2("可用內(nèi)存:{mem_free}\n\n總內(nèi)存:{mem_total}\n\n內(nèi)存占比:{mem_percent}\n\n占用內(nèi)存:{mem_used}".format(mem_free=mem_data[0][0],mem_total=mem_data[0][1],mem_percent=mem_data[0][2],mem_used=mem_data[0][3]), "#000000"),
bar(disk_percent),
pie_base(),
line1(all_time,all_mem_percent)
)
page.render("data_center.html")
db.close()
配色碼-查看RGB顏色查詢對(duì)照表|RGB顏色|三原色配色表 (sojson.com)

數(shù)據(jù)可視化面板預(yù)覽
最后,進(jìn)一步對(duì)大屏布局并設(shè)置一張好看的底圖。
其中,lxml是python的一個(gè)解析庫,支持HTML和XML的解析。
from bs4 import BeautifulSoup
with open("data_center.html", "r+", encoding='utf-8') as html:
html_1 = BeautifulSoup(html, 'lxml')
divs = html_1.select('.chart-container')
divs[0]["style"] = "width:10%;height:10%;position:absolute;top:0;left:2%;"
divs[1]["style"] = "width:40%;height:40%;position:absolute;top:12%;left:2%;"
divs[2]["style"] = "width:35%;height:10%;position:absolute;top:1%;left:30%;"
divs[3]["style"] = "width:40%;height:40%;position:absolute;top:10%;left:25%;"
divs[4]["style"] = "width:40%;height:35%;position:absolute;top:12%;left:55%;"
divs[5]["style"] = "width:30%;height:35%;position:absolute;top:60%;left:5%;"
divs[6]["style"] = "width:60%;height:50%;position:absolute;top:50%;left:35%;"
body = html_1.find("body")
body["style"] = """background-image:url("./img/test.jpg")""" # 背景圖片
html_new = str(html_1)
html.seek(0, 0)
html.truncate()
html.write(html_new)
html.close()
#備注:divs[0]["style"] = "width:10%;height:10%;position:absolute;top:0;left:2%;"即是我們對(duì)寬度、高度、位置、上邊距、左邊距的定義,這里我們用百分比以達(dá)到屏幕自適應(yīng)的效果。
效果圖如下:

至此,一個(gè)實(shí)時(shí)系統(tǒng)信息監(jiān)控面板開發(fā)完畢。其他功能可自行拓展,本文僅演示創(chuàng)建的具體流程,其他細(xì)節(jié)可進(jìn)一步優(yōu)化,如具體到單個(gè)應(yīng)用的監(jiān)測(cè)與控制。
文中包含所有代碼,快動(dòng)手嘗試一下吧。


Python“寶藏級(jí)”公眾號(hào)【Python之王】專注于Python領(lǐng)域,會(huì)爬蟲,數(shù)分,C++,tensorflow和Pytorch等等。
近 2年共原創(chuàng) 100+ 篇技術(shù)文章。創(chuàng)作的精品文章系列有:
日常收集整理了一批不錯(cuò)的 Python 學(xué)習(xí)資料,有需要的小伙可以自行免費(fèi)領(lǐng)取。
獲取方式如下:公眾號(hào)回復(fù)資料。領(lǐng)取Python等系列筆記,項(xiàng)目,書籍,直接套上模板就可以用了。資料包含算法、python、算法小抄、力扣刷題手冊(cè)和 C++ 等學(xué)習(xí)資料!
下面是這本書在京東上的購買鏈接,淘寶天貓等購物平臺(tái)均有銷售,喜歡就看看!
