您好,登錄后才能下訂單哦!
監控數據庫是否可寫,如果你的監控腳本邏輯是,寫入數據庫成功后顯示成功,反之顯示不成功然后報警。那么難題來了,數據庫真的無法寫入了,你的監控腳本的寫入命令也會被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" >中國區zabbix數據庫監控</th> </tr> <td width="100px" nowrap>告警區域</td> <td >中國</td> <tr> </tr> <td width="100px" nowrap>主機名稱</td> <td >xxx.xxx.xxx.xxx</td> <tr> </tr> <td width="100px" nowrap>告警項目</td> <td >zabbix數據庫監控</td> <tr> </tr> <td width="100px" nowrap>告警級別</td> <td bgcolor=red >嚴重</td> <tr> </tr> <td width="100px" nowrap>告警狀態</td> <td bgcolor=red >PROBLEM</td> <tr> </tr> <td width="100px" nowrap>詳細內容</td> <td >""" + mail_result + """</td> <tr> <td width="100px" nowrap>發生時間</td> <td >""" + 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)
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。