1.前提创建数据库和表格式
[root@python ~]# mysql -uroot -pcentos
mysql> create database memory;
mysql> use memory;
mysql> create table memory (memory int,time varchar(50));
2.编写每睡眠一秒就将系统use_mem内存写入数据库
[root@python ~]# cat mem.py
#!/usr/bin/env python
#-*- coding: UTF-8 -*-
import time #导入时间模块
import MySQLdb as mysql #导入MySQLdb模块
db=mysql.connect(user='root',passwd='centos',db='memory',host='localhost') #连接数据库
cursor=db.cursor() #创建游标对象
def getMem():
f = open('/proc/meminfo')
total = int(f.readline().split()[1])
free = int(f.readline().split()[1])
buffer = int(f.readline().split()[1])
cache = int(f.readline().split()[1])
mem_used = total - free - buffer - cache
cur_time =time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
sql = 'insert into memory (memory, time) value (%s,%s)'%(mem_used,cur_time)
cursor.execute(sql) #执行sql语句
print 'ok'
while True:
getMem()
time.sleep(1) # sleep 1 second
3.执行脚本,查看数据库
转载于:https://blog.51cto.com/1767340368/2092040