python编程练习之四——获取系统内存、CPU、磁盘、平均负载信息并保存到数据库中

来源:互联网 发布:恩施二手淘宝 编辑:程序博客网 时间:2024/06/05 01:20

准备工作

  • 安装mariadb
  • 安装MySQL-python
  • 测试python中可以导入MySQL并能正常连接数据库
  • 拥有pycharm 开发工具

说明

  • 结果存在数据库 disk_used_db 中的 disk_used_info 表中
  • 程序运行开始若已存在上述数据库可table,则会询问用户使用已存在的数据库还是丢弃已有数据库或者table,另行建立
  • 该函数未写读取数据库内容的函数,需另行读取
  • 每隔5s刷新一次数据,并写入数据库中,30s询问一次是否继续

开始我们的工作

1.项目开始——创建包

在开发环境下新建一个python的包,包内共需要六个python文件:Average_load.py ,conf.py ,cpu_used.py , disk_used.py , mem_used.py ,  main.py 结构如下:

这里写图片描述

2.数据库初始化信息:conf.py

user="root"passwd="redhat"host="127.0.0.1"port=3306

3.读取CPU使用情况:cpu_used.py

import osdef get_cpu_used():    f = os.popen("top -bi -n 1| awk '{print $2,$4}'").read().split('\n')[2]    return f.read()

4.读取平均负载情况:Average_load.py

import osdef aver_load():    f = os.popen("uptime | sed 's/,//g' | awk '{print $8,$9,$10}'")    return f.read().strip()

5.读取磁盘使用情况:disk_used.py

import osdef get_disk_used():    f=os.popen("df -h | head -2 | tail -1 |awk '{print $5}'")    return f.read()

6.读取内存使用情况:mem_used.py

import osdef get_mem_used():    f = os.popen("free -m |grep Mem |awk '{print $2,$3}'")    return f.read()

7.主函数:main.py

from __future__ import divisionimport MySQLdb as mysqlimport time, confimport disk_used, mem_used, cpu_used, Average_loadconn = mysql.connect(user=conf.user, passwd=conf.passwd, host=conf.host, port=conf.port)cur = conn.cursor()try:    cur.execute("create database disk_used_db")except Exception, e:    choise = raw_input("database disk_used_db exists,drop? (Y/N)")    if choise.lower() == "y":        cur.execute("drop database disk_used_db")        cur.execute("create database disk_used_db")        print "drop old database and creating new database(disk_used_db)... "        time.sleep(1)        print "creat new database success!!"    else:        print "used old database"conn.select_db("disk_used_db")try:    cur.execute("create table disk_used_info(name varchar(20),disk_used varchar(30),mytime varchar(50))")except Exception, e1:    choise1 = raw_input("table disk_used_info exists,drop? (Y/N)")    if choise1.lower() == "y":        cur.execute("drop table disk_used_info")        cur.execute("create table disk_used_info(name varchar(20),disk_used varchar(30),mytime varchar(50))")        print "drop old table and creating new table(disk_used_info)... "        time.sleep(1)        print "creat new table success!!"    else:        print "used old table"sql_in = "insert into disk_used_info values(%s,%s,%s)"start_time = time.time()while True:    disk_used_info = disk_used.get_disk_used().strip()    memuseinfos = map(int, mem.mem_usage().split(' '))    memtotal = memuseinfos[0]    memused = memuseinfos[1]    mem_used_tmp = memused / memtotal    memory_used = "%.2f%%" % (mem_used_tmp * 100)    cpuinfo = cpu_used.get_cpu_used()    cpuinfo_tmp = cpuinfo.split(' ')    cpu_used_tmp = "%.2f%%" % (cpuinfo_tmp * 100)    load = Average_load.aver_load().split(' ')    load1s = load[0] + '%'    load5s = load[1] + '%'    load15s = load[2] + '%'    now = time.asctime()    cur.execute(sql_in, ("disk_used", disk_used_info, now))    cur.execute(sql_in, ("mem_used", memory_used, now))    cur.execute(sql_in, ("cpu_used", cpu_used_tmp, now))    cur.execute(sql_in, ("Average_load(1s)", load1s, now))    cur.execute(sql_in, ("Average_load(5s)", load5s, now))    cur.execute(sql_in, ("Average_load(15s)", load5s, now))    conn.commit()    print "saving....."    time.sleep(5)           ##fresh per 5 second    end_time = time.time()    if end_time - start_time >= 30:        selc = raw_input("Data stored for 30 seconds has been stored,continue?(Y/N)")        if selc.lower() == "y":            start_time = time.time()            continue        else:            breakcur.close()conn.close()
阅读全文
0 0
原创粉丝点击