1. 程式人生 > >Python 獲取CentOS7的內存使用率並寫入mysql

Python 獲取CentOS7的內存使用率並寫入mysql

linux mysql

由於Centos7和6的系統變化挻大的,所以先看看Centos7的內存信息是怎麽樣的。

系統版本:

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

查看內存信息:其實只需要關註前5行即可;

[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 代碼:

#/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模塊

pip install pymysql


創建數據庫以及表:

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裏查詢一下;

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的表只用了兩個字段,一個內存使用率,這個值是以兆為單位的,另一個就是時間了。

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]>



Python 獲取CentOS7的內存使用率並寫入mysql