首页 > 代码库 > 用python监控mysql数据库是否可写

用python监控mysql数据库是否可写

监控数据库是否可写,如果你的监控脚本逻辑是,写入数据库成功后显示成功,反之显示不成功然后报警。那么难题来了,数据库真的无法写入了,你的监控脚本的写入命令也会被mysql hang住,一直卡在那里,直到天荒地老,根本无法实现报警。那换个思路,如果设置个超时时间,是不是更好。

#!/usr/bin/env python
# -*-coding:utf8-*-
import MySQLdb
import re
import smtplib
import json
from email.mime.text 
import MIMEText
import sys
import time
import multiprocessing
reload(sys)
sys.setdefaultencoding(‘utf8‘)


def mysql_select(sql, pipe):
    try:
        conn = MySQLdb.connect(host=‘xxx.xxx.xxx.xxx‘,user=‘xxxx‘,passwd=‘xxxx‘,db=‘xxxx‘,port=xxxx,charset=‘utf8‘,connect_timeout=10)
        cursor = conn.cursor()
        cursor.execute(sql)
        result = cursor.fetchall()
        cursor.close()
        conn.commit()
        conn.close()
        pipe.send(‘successful‘)    
     except Exception,e:
        pipe.send("zabbix 数据库异常: %s" % e) 

def query_with_timeout(sql):
    pipe_out, pipe_in = multiprocessing.Pipe(False)
    subproc = multiprocessing.Process(target=mysql_select,args=(sql, pipe_in))
    subproc.start()
    subproc.join(timeout=3)    
    if pipe_out.poll():
        ex_c = pipe_out.recv()    
    else:
        ex_c = "zabbix 数据库无法写入"
    subproc.terminate()    
    #raise Exception("Query %r ran for >%r" % (sql, 5))
    raise Exception(ex_c)
###
    
def se_mail(mail_result):
    now_time = time.strftime(‘%Y-%m-%d %H:%M:%S‘,time.localtime(time.time()))
    sys.setdefaultencoding(‘utf-8‘)
    SUBJECT = "数据库监控"
    TO = "xxxx@ptthink.com"
    FROM = "ooooo@ptmind.com"
    msg = MIMEText("""
        <html>
            <head>
            </head>
            <body>
                <table width="800" border="1" cellspacing="0" cellpadding="4">
                    <tr>
                       <th bgcolor="#00FFFF" height="1"  colspan="4" align="center"  style="font-size:15px">中国区zabbix数据库监控</th>
                    </tr>
                         <td  width="100px"  style="font-size:15px"  nowrap>告警区域</td>
                         <td  style="font-size:15px">中国</td>
                    <tr>
                    </tr>
                         <td  width="100px"  style="font-size:15px"  nowrap>主机名称</td>
                         <td  style="font-size:15px">xxx.xxx.xxx.xxx</td>
                    <tr>
                    </tr>
                         <td  width="100px"  style="font-size:15px"  nowrap>告警项目</td>
                         <td  style="font-size:15px">zabbix数据库监控</td>
                    <tr>
                    </tr>
                         <td  width="100px"  style="font-size:15px"  nowrap>告警级别</td>
                         <td  bgcolor=red style="font-size:15px">严重</td>
                    <tr>
                    </tr>
                         <td  width="100px"  style="font-size:15px"  nowrap>告警状态</td>
                         <td  bgcolor=red style="font-size:15px">PROBLEM</td>
                    <tr>
                    </tr>
                         <td  width="100px"  style="font-size:15px"  nowrap>详细内容</td>
                         <td  style="font-size:15px">""" + mail_result + """</td>
                    <tr>
                         <td  width="100px"  style="font-size:15px"  nowrap>发生时间</td>
                         <td  style="font-size:15px">""" + now_time + """</td>
                    </tr>
                </table>
            </body>
        </html>""","html","utf-8")
    msg[‘Subject‘] = SUBJECT
    msg[‘From‘]=FROM
    msg[‘To‘]=TO    
    try:
        server = smtplib.SMTP(‘localhost‘)
        server.sendmail(FROM, TO, msg.as_string())
        server.quit()        
        print "邮件发送成功!"
    except Exception, e:        
        print "失败:"+str(e)
        
###
    
if __name__ == ‘__main__‘:    
    #创建监控数据库连接,与是否可写,的监控表,下面是创建语句
    #sql_user_info = """
    #CREATE TABLE IF NOT EXISTS db_check_table (
    #itemid INT(20),
    #applicationid INT(20),
    #hostid INT(20),
    #name  VARCHAR(255),
    #du_name  VARCHAR(255),
    #item_name   VARCHAR(255)
    #)
    #"""
    insert_sql = """insert into db_check_table values (‘10211‘,‘13564‘,‘456789‘,‘test-172.5.6.7‘,‘cpu‘,‘cpu ldie‘)"""   
    try:
        query_with_timeout(insert_sql)    
    except Exception,e:
        mail_result = str(e)        
        if mail_result != "successful" :
            se_mail(mail_result)


本文出自 “杜云龙” 博客,请务必保留此出处http://duyunlong.blog.51cto.com/1054716/1921655

用python监控mysql数据库是否可写