通过Python收集汇聚MySQL 表信息

一.需求

统计收集各个实例上table的信息,主要是表的记录数及大小。

收集的范围是cmdb中所有的数据库实例。

通过Python收集汇聚MySQL 表信息

二.公共基础文件说明

1.配置文件

配置文为db_servers_conf.ini,假设cmdb的DBServer为119.119.119.119,单独存放收集监控数据的DBserver为110.110.110.110. 这两个DB实例的访问用户名一样,定义在了[uid_mysql] 部分,需要去收集的各个DB实例,用到的账号密码是另一个,定义在了[collector_mysql]部分。

[uid_mysql]
dbuid = 用*户*名
dbuid_p_w_d = 相*应*密*码

[cmdb_server]
db_host = 119.119.119.119
db_port = 3306

[dbmonitor_server]
db_host = 110.110.110.110
db_port = 3306

[collector_mysql]
collector = DB*实*例*用*户*名
collector_p_w_d = DB*实*例*密*码

2.定义声明db连接

文件为get_mysql_db_connect.py

-*- coding: utf-8 -*-

import sys
import os
import configparser
import pymysql

获取连接串信息
def mysql_get_db_connect(db_host, db_port):
    db_host = db_host
    db_port = db_port

    db_ps_file = os.path.join(sys.path[0], "db_servers_conf.ini")
    config = configparser.ConfigParser()
    config.read(db_ps_file, encoding="utf-8")
    db_user = config.get('uid_mysql', 'dbuid')
    db_pwd = config.get('uid_mysql', 'dbuid_p_w_d')

    conn = pymysql.connect(host=db_host, port=db_port, user=db_user, password=db_pwd,  connect_timeout=5, read_timeout=5, write_timeout=5)

    return conn

获取连接串信息
def mysql_get_collectdb_connect(db_host, db_port):
    db_host = db_host
    db_port = db_port

    db_ps_file = os.path.join(sys.path[0], "db_servers_conf.ini")
    config = configparser.ConfigParser()
    config.read(db_ps_file, encoding="utf-8")
    db_user = config.get('collector_mysql', 'collector')
    db_pwd = config.get('collector_mysql', 'collector_p_w_d')

    conn = pymysql.connect(host=db_host, port=db_port, user=db_user, password=db_pwd,  connect_timeout=5, read_timeout=5, write_timeout=5)

    return conn

3.定义声明访问db的操作

文件为mysql_exec_sql.py,注意需要导入上面的model。

-*- coding: utf-8 -*-

import get_mysql_db_connect

def mysql_exec_dml_sql(db_host, db_port, exec_sql):
    conn = mysql_get_db_connect.mysql_get_db_connect(db_host, db_port)
    with conn.cursor() as cursor_db:
        cursor_db.execute(exec_sql)
        conn.commit()
        ##需要显式关闭
        cursor_db.close()
        conn.close()

def mysql_exec_select_sql(db_host, db_port, exec_sql):
    conn = mysql_get_db_connect.mysql_get_db_connect(db_host, db_port)
    with conn.cursor() as cursor_db:
        cursor_db.execute(exec_sql)
        sql_rst = cursor_db.fetchall()
        ##显式关闭conn
        cursor_db.close()
        conn.close()

    return sql_rst

def mysql_exec_select_sql_include_colnames(db_host, db_port, exec_sql):
    conn = mysql_get_db_connect.mysql_get_db_connect(db_host, db_port)
    with conn.cursor() as cursor_db:
        cursor_db.execute(exec_sql)
        sql_rst = cursor_db.fetchall()
        col_names = cursor_db.description
    return sql_rst, col_names

三.主要代码

3.1 创建保存数据的脚本

用来保存收集表信息的表:table_info

create table table_info (
  id int(11) NOT NULL AUTO_INCREMENT,
  host_ip varchar(50) NOT NULL DEFAULT '0',
  port varchar(10) NOT NULL DEFAULT '3306',
  db_name varchar(100) NOT NULL DEFAULT ''   COMMENT '数据库名字',
  table_name varchar(100) NOT NULL DEFAULT '' COMMENT '表名字',
  table_rows bigint NOT NULL DEFAULT 0 COMMENT '表行数',
  table_data_length bigint,
  table_index_length bigint,
  table_data_free bigint,
  table_auto_increment bigint,
  creator varchar(50) NOT NULL DEFAULT '',
  create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  operator varchar(50) NOT NULL DEFAULT '',
  operate_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
 PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4
;

收集过程,如果访问某个实例异常时,将失败的信息保存到表 gather_error_info 中,以便跟踪分析。

create table gather_error_info (
  id int(11) NOT NULL AUTO_INCREMENT,
  app_name varchar(150) NOT NULL DEFAULT '报错的程序',
  host_ip varchar(50) NOT NULL DEFAULT '0',
  port varchar(10) NOT NULL DEFAULT '3306',
  db_name varchar(60) NOT NULL DEFAULT '0' COMMENT '数据库名字',
  error_msg varchar(500) NOT NULL DEFAULT '报错的程序',
  status int(11) NOT NULL DEFAULT '2',
  creator varchar(50) NOT NULL DEFAULT '',
  create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  operator varchar(50) NOT NULL DEFAULT '',
  operate_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
 PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;

3.2 收集的功能脚本

定义收集 DB_info的脚本 collect_tables_info.py

-*- coding: utf-8 -*-

import sys
import os
import datetime
import configparser
import pymysql
import mysql_get_db_connect
import mysql_exec_sql
import mysql_collect_exec_sql
import pandas as pd

def collect_tables_info():
    db_ps_file = os.path.join(sys.path[0], "db_servers_conf.ini")
    config = configparser.ConfigParser()
    config.read(db_ps_file, encoding="utf-8")

    cmdb_host = config.get('cmdb_server', 'db_host')
    cmdb_port = config.getint('cmdb_server', 'db_port')

    monitor_db_host = config.get('dbmonitor_server', 'db_host')
    monitor_db_port = config.getint('dbmonitor_server', 'db_port')

    # 获取需要遍历的DB列表
    exec_sql_1 = """
select  vm_ip_address,port,b.vm_host_name,remark
FROM cmdbdb.mysqldb_instance
 ;
"""

    exec_sql_tablesizeinfo = """
select TABLE_SCHEMA,table_name,table_rows,data_length ,index_length,data_free,auto_increment
from information_schema.tables
where TABLE_SCHEMA not in ('mysql','information_schema','performance_schema','sys')
and TABLE_TYPE ='BASE TABLE';
"""

    exec_sql_insert_tablesize = " insert into monitordb.table_info (host_ip,port,db_name,table_name,table_rows,table_data_length,table_index_length,table_data_free,table_auto_increment) \
VALUES ('%s', '%s','%s','%s', %s ,%s, %s,%s, %s) ;"

    exec_sql_error = " insert into monitordb.gather_db_error (app_name,host_ip,port,error_msg) \
VALUES ('%s', '%s','%s','%s') ;"

    sql_rst_1 = mysql_exec_sql.mysql_exec_select_sql(cmdb_host, cmdb_port, exec_sql_1)
    if len(sql_rst_1):
        for i in range(len(sql_rst_1)):
            rw_host = list(sql_rst_1[i])
            db_host_ip = rw_host[0]
            db_port_s = rw_host[1]
            ##print(type(rw_host))

            ###ValueError: port should be of type int
            db_port = int(db_port_s)
            try:
              sql_rst_tablesize = mysql_collect_exec_sql.mysql_exec_select_sql(db_host_ip, db_port, exec_sql_tablesizeinfo)
              ##print(sql_rst_tablesize)
              if len(sql_rst_tablesize):
                  for i in range(len(sql_rst_tablesize)):
                      rw_tableinfo = list(sql_rst_tablesize[i])
                      rw_db_name = rw_tableinfo[0]
                      rw_table_name = rw_tableinfo[1]
                      rw_table_rows = rw_tableinfo[2]
                      rw_data_length = rw_tableinfo[3]
                      rw_index_length = rw_tableinfo[4]
                      rw_data_free = rw_tableinfo[5]
                      rw_auto_increment = rw_tableinfo[6]

                      ##print(rw_auto_increment)
                      ##Python中对变量是否为None的判断
                      if rw_auto_increment is None:
                         rw_auto_increment = 0
                      ###一定要有一个exec_sql_insert_table_com,如果是exec_sql_insert_tablesize = exec_sql_insert_tablesize  %  ( db_host_ip.......

                      ####则提示报错:报错信息是 TypeError: not all arguments converted during string formatting
                      exec_sql_insert_table_com = exec_sql_insert_tablesize  %  ( db_host_ip , db_port_s, rw_db_name, rw_table_name , rw_table_rows , rw_data_length , rw_index_length , rw_data_free , rw_auto_increment)
                      print(exec_sql_insert_table_com)
                      sql_insert_rst_1 = mysql_exec_sql.mysql_exec_dml_sql(monitor_db_host, monitor_db_port, exec_sql_insert_table_com)
                      #print(sql_insert_rst_1)
            except:
              ####print('TypeError的错误信息如下:' + str(TypeError))
              print(db_host_ip +'  '+str(db_port) + '登入异常无法获取table信息,请检查实例和访问账号!')
              exec_sql_error_sql = exec_sql_error  %  ( 'collect_tables_info',db_host_ip , str(db_port),'登入异常,获取table信息失败,请检查实例和访问的账号!!!' )
              sql_insert_err_rst_1 = mysql_exec_sql.mysql_exec_dml_sql(monitor_db_host, monitor_db_port, exec_sql_error_sql)
        ##print(sql_rst_1)
    else:
        print('查询无结果集')

collect_tables_info()

Original: https://www.cnblogs.com/xuliuzai/p/15327808.html
Author: 东山絮柳仔
Title: 通过Python收集汇聚MySQL 表信息

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/622589/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

  • 部署tomcat

    tomcat tomcat 一、tomcat是什么 二、tomcat部署 1.实现访问java测试网页 2.能够成功登录到tomcat首页中的host manager、server…

    数据库 2023年6月14日
    043
  • 新建vue项目

    1、CMD中输入命令行 vue ui 打开一个创建项目的窗口 2、安装插件element ui 3、Idea 打开这个项目即可 4、Idea 运行vue项目 npm run ser…

    数据库 2023年6月9日
    092
  • 数据火器库八卦系列之瑞士军刀随APP携带的SQLite

    来源:云数据库技术 数据库打工仔喃喃自语的八卦历史 为导弹巡洋舰设计,用在手机上的数据库 Small and Simple, and Better 如何看出是自己的娃:产品定位,特…

    数据库 2023年6月11日
    096
  • Mybatis第三方PageHelper分页插件原理

    欢迎关注公号:BiggerBoy,看更多文章 往期精品 此时commentAnalyses为Page对象(PageHelper插件包内定义的) 而Page对象继承自JDK中的Arr…

    数据库 2023年6月11日
    076
  • 微信登录前端开发指南

    使用场景 微信公众号内嵌H5网页调用微信登录 在微信浏览器中的网页唤起微信登录界面 详情可以查阅微信登录官方文档 链接地址 功能思路 后台先在微信给开发者提供的测试账号平台上创建应…

    数据库 2023年6月11日
    068
  • JVM-堆

    堆 JAVA技术交流群:737698533 堆核心概述 此内存区域的唯一目的就是存放对象实例 一个JVM实例只存在一个堆内存,堆也是Java内存管理的核心区域。 Java堆区在JV…

    数据库 2023年6月16日
    0100
  • 调试Archery连接SQL Server提示驱动错误

    当我们在调试Archery的时候,连接SQL Server 会报错,而MySQL部分没有问题。报错信息如下: Error: (‘01000’, "[01000] [uni…

    数据库 2023年6月16日
    0123
  • 多版本并发控制 MVCC

    介绍多版本并发控制 多版本并发控制技术(Multiversion Concurrency Control,MVCC) 技术是为了解决问题而生的,通过 MVCC 我们可以解决以下几个…

    数据库 2023年6月11日
    0126
  • SpringWeb 拦截器

    前言 spring拦截器能帮我们实现验证是否登陆、验签校验请求是否合法、预先设置数据等功能,那么该如何设置拦截器以及它的原理如何呢,下面将进行简单的介绍 1.设置 HandlerI…

    数据库 2023年6月16日
    069
  • 5 float f = 3.4,是否正确

    不正确,赋值运算符 “=” 左右两边的精度类型不匹配。 Java中,有小数点的默认被存储为double类型,即双精度;而float类型的变量为单精度。 可以…

    数据库 2023年6月6日
    060
  • MySQL–用通配符进行过滤(LIKE操作符)

    1、LIKE操作符 怎样搜索产品名中包含文本anvil的所有产品?用简单的比较操作符肯定不行,必须使用通配符。利用通配符可创建比较特定数据的搜索模式。在这个例子中,如果你想找出名称…

    数据库 2023年6月16日
    069
  • 计算机组成原理——概述篇

    计算机发展历史 电子管计算机(1946 年——1958 年) 第一台计算机为ENIAC 诞生于美国宾夕法尼亚大学 特点: 集成度小,空间占用大 功耗高,运行速度慢 操作复杂,更换程…

    数据库 2023年6月16日
    051
  • docker的相关命令

    docker的相关命令 1.安装docker: (1)yum -y install docker ​ sudo sh get-docker.sh 2.从远程拉取应用的镜像源: do…

    数据库 2023年6月16日
    067
  • python tkiner实现自动打包程序

    环境 python3.x 使用前请确保安装pyinstaller库 本程序还未完善,可以自行完善 若要使用加密,请自行安装cryptodome库 python;gutter:tru…

    数据库 2023年6月11日
    083
  • 条件控制

    1. 顺序结构 java代码顺序执行 2. 选择结构 if语句 格式 if(结果为booblean类型的表达式){ 语句体; } if(结果为booblean类型的表达式){ 语句…

    数据库 2023年6月14日
    048
  • pg数据库匹配正则

    select ‘41142619960609331x’ ~ ‘^[1-9]\d{5}\d{4}((0[1-9])|(10|11|12))(([0…

    数据库 2023年6月16日
    076
亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球