整体思想
1、使用python包psutil 获取linux服务器CPU、内存等相关数据2、数据保存在本地或者保存在数据库3、读取数据,使用python包pyecharts画图4、使用Flask,页面前端访问
一、pstuil 的安装和使用,保存数据
pip install pstuil
import psutilimport timeimport MySQLdb as mysqldb = mysql.connect(user="test", passwd="123456", db="test", host="200.200.200.200")db.autocommit(True)cur = db.cursor()def getinfo():mem = psutil.virtual_memory()memtotal = mem.totalmemfree = mem.freemempercent = mem.percentmemused = mem.usedcpu = psutil.cpu_percent(1)return memtotal,memfree,memused,mempercent,cpuif __name__== "__main__":while True:try:memtotal,memfree,memused,mempercent,cpu =getinfo()t = int(time.time())sql = 'insert into stat (mem_free,mem_usage,mem_total,mempercent,cpu,time) value (%s,%s,%s,%s,%s,%s)'%(memfree,memused,memtotal,mempercent,cpu,t)cur.execute(sql)time.sleep(10)except Exception as e:print(e)
其中涉及到mysql数据库的使用会报错,按如下修复当然其实也可以不用。
import MySQLdb as mysql行报错,在前面添加两行
File “/home/python/.virtualenvs/django_py3_1.11/local/lib/python3.5/site-packages/django/db/backends/mysql/base.py”, line 26, in
import MySQLdb as Database
ImportError: No module named ‘MySQLdb’
解决:项目__init__.py中
import pymysqlpymysql.install_as_MySQLdb()
如果不适用数据库:
import psutilimport time# 不适用数据库记录# import pymysql# pymysql.install_as_MySQLdb()# import MySQLdb as mysql# db = mysql.connect(user="zero", passwd="", db="", host="200.200.200.200")# db.autocommit(True)# cur = db.cursor()def getinfo():''':return:memtotal: 总内存memfree: 空闲内存memused: Linux: total - free,已使用内存mempercent: 已使用内存占比cpu: 各个CPU使用占比'''mem = psutil.virtual_memory()memtotal = mem.totalmemfree = mem.freemempercent = mem.percentmemused = mem.usedcpu = psutil.cpu_percent(percpu=True)return memtotal, memfree, memused, mempercent, cpuif __name__ == "__main__":while True:try:memtotal, memfree, memused, mempercent, cpu = getinfo()t = int(time.time())# sql = 'insert into stat (mem_free,mem_usage,mem_total,mempercent,cpu,time) value (%s,%s,%s,%s,%s,%s)'%(memfree,memused,memtotal,mempercent,cpu,t)# cur.execute(sql)print(memtotal, memfree, memused, mempercent, cpu)time.sleep(10)except Exception as e:print(e)
转载:
/lhh08hasee/article/details/82788373