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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python 获取CentOS7的内存使用率并写入mysql相关的知识,希望对你有一定的参考价值。

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

系统版本:

[[email protected] ~]# cat /etc/redhat-release 
CentOS Linux release 7.2.1511 (Core) 
[[email protected] ~]#

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

[[email protected] ~]# 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
[[email protected] ~]# 

[[email protected] ~]# free -m
              total        used        free      shared  buff/cache   available
Mem:           2001         762          81           0        1156        1035
Swap:           511         142         369
[[email protected] ~]#

内存使用率的计算: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 [email protected]'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的主要内容,如果未能解决你的问题,请参考以下文章

HTTP协议与使用Python获取数据并写入MySQL

pyqt5 qimage 读取内存数据

vue获取内存中的值并写入

Python-Opencv 在内存缓冲区上写入 x264 视频

通过python自动化获取服务器信息,并写入到excel

python 获取登录态网络数据并写入本地