设为首页 加入收藏

TOP

用Python对MySQL同步状态进行监控(一)
2015-11-21 01:38:00 来源: 作者: 【 】 浏览:2
Tags:Python MySQL 同步 状态 进行 监控

用Python对MySQL同步状态进行监控

使用Python对MySQL数据库服务器是否可访问,及主从同步是否中断进行监控,是一件非常简单的事情。感谢Python给我们带来了如此简单,强大,快捷的开发环境。

本文使用到的Python模块
使用telnetlib校验服务器是否可被访问
使用SMTP向管理员发送通知邮件
使用MySQL官方的驱动对数据库进行访问
使用optparse实现命令行参数的提取

实现原理
使用optparse模块获取命令行参数。读取defaults-file设置文件内容(如果存在),使用参数覆盖defaults-file的值(如果传递参数,如:?host, ?user, ?to之类)。

直接去连MySQL等待是否能进行访问的返回结果太慢了,所以使用telnet对服务器的连通性进行验证。可以设置等待时间,可控性高一些。

当服务器工作正常,使用MySQL与服务器进行连接,获取主从同步的状态。

将获取服务器的异常状态信息(服务器无法访问,主从同步的状态中断),使用SMTP发送给管理员,并把造成中断同步的异常信息一同发送到管理员的邮箱中。


Created with Rapha?l 2.1.2 start telnet host:port connect? slave status slave? end notify yes no yes no

slavecheckpoint.py

coding=utf-8
"""
数据库同步状态侦测
MySQL数据库同步复制状态监测脚本。可配合Linux下的crond进行定时监测。如果同步
状态异常,侧使用邮件通知管理员,并将造成同步中断的错误信息也包含到邮件当中,管
理员可即时通过错误信息直接定位异常。

实例:
python slavecheckpoint.py --defaults-file=/etc/slave.cnf --to=xxxx@abc.com

===FILE:slave.cnf===========
[config]
smtp_host=smtp.163.com
from=消息中心
host=localhost
"""

import mysql.connector
from mysql.connector import errorcode
import telnetlib
import smtplib
from email.mime.text import MIMEText
import optparse
from ConfigParser import ConfigParser
import os,time,sys

class SlaveStatu:
    __instance__ = None
    __error__ = []

    def __init__(self,*args,**kwargs):
        self.__config__ = {
            "host":"localhsot",
            "user":"root",
            "password":"",
            "port":3306,
            "smtp_host":"localhost",
            "smtp_user":"",
            "smtp_password":"",
            "from":"admin@localhost",
            "to":""
        }

        #优先读取设置文件中的值
        if not kwargs["defaults_file"] is None:
            defaults_file = self.__read_defaults_file__( kwargs["defaults_file"] )
            del kwargs["defaults_file"]

        #使用参数的设置去覆盖设置文件的值
        for key,val in kwargs.items():
            if not val is None and len(val) > 0:
                self.__config__[key] = val

    def __configParseMySQL__(self):
        """
        提取数据库的设置
        :return: dict
        """
        return {
            "host"     : self.__config__["host"],
            "port"     : self.__config__["port"],
            "user"     : self.__config__["user"],
            "password" : self.__config__["password"]
        }

    def __configParseSMTP__(self):
        """
        提取SMTP邮件设置
        :return: dict
        """
        return {
            "smtp_host": self.__config__["smtp_host"],
            "smtp_user": self.__config__["smtp_user"],
            "smtp_password": self.__config__["smtp_password"],
            "from": self.__config__["from"],
            "to": self.__config__["to"]
        }

    def __read_defaults_file__( self, filePath ):
        """
        加载设置文件设置的值
        :param filePath: 设置文件路径
        :return:
        """
        section = "config"
        if os.path.exists( filePath ):
            cnf = ConfigParser()
            cnf.read( filePath )
            options = cnf.options( section )

            for key in options:
                self.__config__[key] = cnf.get( section, key )


    def telnet( self, host, port, timeout=5 ):
        """
        测试服务器地址和端口是否畅通
        :param host: 服务器地址
        :param port: 服务器端口
        :param timeout: 测试超时时间
        :return: Boolean
        """
        try:
            tel = telnetlib.Telnet( host, port, timeout )
            tel.close()
            return True
        except:
            return False

    def connect(self):
        """
        创建数据库链接
        """
        try:
            config = self.__configParseMySQL__()
            if self.telnet( config["host"],config["port"]):
                self.__instance__ = mysql.connector.connect( **config )
                return True
            else:
                raise Exception("unable connect")
        except:
            self.__error__.append( "无法连接服务器主机: {host}:{port}".format( host=config[
                    "host"], port=config["port"]) )
            return False

    def isSlave(self
首页 上一页 1 2 下一页 尾页 1/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇mysql创建、删除用户与授权(linux.. 下一篇MySQL查看运行时间

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: