Python 获取CentOS7的内存使用率并写入mysql

由于Centos7和6的系统变化挻大的,所以先看看Centos7的内存信息是怎么样的。

系统版本:

1
2
3
[root@docker ~]# cat /etc/redhat-release 
CentOS Linux release 7.2.1511 (Core) 
[root@docker ~]#

查看内存信息:其实只需要关注前5行即可;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
[root@docker ~]# cat /proc/meminfo 
MemTotal:        2049248 kB
MemFree:           85408 kB
MemAvailable:    1061812 kB
Buffers:          138044 kB
Cached:           885028 kB
SwapCached:        33308 kB
Active:           881088 kB
Inactive:         832516 kB
Active(anon):     315948 kB
Inactive(anon):   375464 kB
Active(file):     565140 kB
Inactive(file):   457052 kB
Unevictable:           0 kB
Mlocked:               0 kB
SwapTotal:        524284 kB
SwapFree:         377836 kB
Dirty:                24 kB
Writeback:             0 kB
AnonPages:        659500 kB
Mapped:            71544 kB
Shmem:               876 kB
Slab:             160772 kB
SReclaimable:     123148 kB
SUnreclaim:        37624 kB
KernelStack:        7408 kB
PageTables:        20580 kB
NFS_Unstable:          0 kB
Bounce:                0 kB
WritebackTmp:          0 kB
CommitLimit:     1548908 kB
Committed_AS:    2998548 kB
VmallocTotal:   34359738367 kB
VmallocUsed:      156648 kB
VmallocChunk:   34359541760 kB
HardwareCorrupted:     0 kB
AnonHugePages:    434176 kB
HugePages_Total:       0
HugePages_Free:        0
HugePages_Rsvd:        0
HugePages_Surp:        0
Hugepagesize:       2048 kB
DirectMap4k:       73664 kB
DirectMap2M:     2023424 kB
DirectMap1G:           0 kB
[root@docker ~]
 
[root@docker ~]# free -m
              total        used        free      shared  buff/cache   available
Mem:           2001         762          81           0        1156        1035
Swap:           511         142         369
[root@docker ~]#

内存使用率的计算:mem_used=MemTotal-MemFree-Buffers


python 代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#/usr/bin/env python                                                                
import time                                                                          
import pymysql as mysql                                                              
db = mysql.connect(user='dba',passwd='123456',db='memory',host='localhost')         
db.autocommit(True)                                                                  
cur = db.cursor()                                                                    
                                                                                      
def getMem():                                                                        
    f = open('/proc/meminfo')                                                        
    total = int(f.readline().split()[1])                                             
    free = int(f.readline().split()[1])                                              
    MemAvailable = f.readline().split()                                              
    cache = int(f.readline().split()[1])                                             
    mem_use = total-free-cache                                                       
    t = time.time()                                                                  
    sql = 'insert into memory(memory,time) values(%s,%s)' %(mem_use/1024,t)          
    cur.execute(sql)                                                                 
    #print mem_use                                                                   
    print ('ok')
                                                                      
while True:                                                                          
    time.sleep(1)                                                                    
    getMem()


安装pymysql模块

1
pip install pymysql


创建数据库以及表:

1
2
3
4
5
6
7
MariaDB [(none)]> create database memory charset=utf8;
MariaDB [(none)]> use memory;
MariaDB [(none)]> CREATE TABLE `memory` (    `memory` int(11) DEFAULT NULL,    `time` int(11) DEFAULT NULL  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
 
授权用户
MariaDB [(none)]> grant all on *.* to dba@'localhost' identified by '123456';
MariaDB [(none)]> flush privileges;

执行python代码,每隔一秒就会打印一个ok到终端,然后在Mysql里查询一下;

1
2
3
4
5
6
7
8
9
10
11
MariaDB [memory]> select * from memory limit 5;
+--------+------------+
| memory | time       |
+--------+------------+
|   1775 | 1513906229 |
|   1775 | 1513906230 |
|   1775 | 1513906231 |
|   1775 | 1513906232 |
|   1775 | 1513906233 |
+--------+------------+
5 rows in set (0.00 sec)

注:Mysql的表只用了两个字段,一个内存使用率,这个值是以兆为单位的,另一个就是时间了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
MariaDB [(none)]> use memory;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
 
Database changed
MariaDB [memory]> show create table memory\G
*************************** 1. row ***************************
       Table: memory
Create Table: CREATE TABLE `memory` (
  `memory` int(11) DEFAULT NULL,
  `time` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
1 row in set (0.00 sec)
 
MariaDB [memory]>



本文转自 dengaosky 51CTO博客,原文链接:http://blog.51cto.com/dengaosky/2053186,如需转载请自行联系原作者

上一篇:Java架构师教你写代码(二) - 使用建造者替代多参数的构造器(下)


下一篇:不是所有的大作业都叫微信抢票大作业