使用python进行Linux服务器监测,画CPU使用率和内存占用图

整体思想

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
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值