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("""

中国区zabbix数据库监控
发生时间""" + now_time + """

""","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数据库是否可写

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

本条技术文章来源于互联网,如果无意侵犯您的权益请点击此处反馈版权投诉

本文系统来源:http://duyunlong.blog.51cto.com/1054716/1921655

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值