使用python进行Linux服务器监测,画CPU使用率和内存占用图
整体思想1、使用python包psutil 获取linux服务器CPU、内存等相关数据2、数据保存在本地或者保存在数据库3、读取数据,使用python包pyecharts画图4、使用Flask,页面前端访问转载:https://blog.csdn.net/lhh08hasee/article/details/82788373...
·
整体思想
1、使用python包psutil 获取linux服务器CPU、内存等相关数据
2、数据保存在本地或者保存在数据库
3、读取数据,使用python包pyecharts画图
4、使用Flask,页面前端访问
一、pstuil 的安装和使用,保存数据
pip install pstuil
import psutil
import time
import MySQLdb as mysql
db = 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.total
memfree = mem.free
mempercent = mem.percent
memused = mem.used
cpu = psutil.cpu_percent(1)
return memtotal,memfree,memused,mempercent,cpu
if __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 pymysql
pymysql.install_as_MySQLdb()
如果不适用数据库:
import psutil
import 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.total
memfree = mem.free
mempercent = mem.percent
memused = mem.used
cpu = psutil.cpu_percent(percpu=True)
return memtotal, memfree, memused, mempercent, cpu
if __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)
转载:
https://blog.csdn.net/lhh08hasee/article/details/82788373
更多推荐
已为社区贡献2条内容
所有评论(0)