用Python写的一个MySQL数据库监测系统

原理很简单,定期连接数据库,如果出现错误,发送邮件到指定邮箱中。

import MySQLdb
import sys
import os
import time
import smtplib
#该程序用于检测数据库服务器是否允许正常,服务器当机的话会往目的邮箱发送一封邮件
#使用说明:
#1:在服务器数据库上建立数据库test1(可以不含任何表)
#2:使用python monitorDB.py 用户名 密码调用该程序,如果用户名为root,密码为sa,则为python monitorDB.py root sa


def conn(user,pwd):
    try:
        conn=MySQLdb.connect(host='localhost',user=user,passwd=pwd,db='test1')
        return 1
    except:
        return 0
def send():
    mail_server='smtp.gmail.com'    #邮件服务器,这里使用gmail
    try:
        s=smtplib.SMTP(mail_server)
        s.starttls()
        s.login('XXXXX','XXXXX')#用户名和密码,如果test@gmail.com密码为111.则为s.login('test','111')
        s.sendmail('XXXX@gmail.com','XXXXX@gmail.com','DB server crashes!')#参数为发送者,接受者,消息
        s.quit
        print "mail have sended!"
    except:
        print "mail send error!"
       
def monitor(user,pwd):
    havesend=0
    while True:
        time.sleep(60)#每隔60秒检查一次,可以通过括号内的值来改变时间
        if conn(user,pwd)==1:
            havesend=0
            print "server is normally working! "
            continue
        else:
            print "server crashes "
            if havesend==0:
                havesend=1
                send()
                continue
            elif havesend==1:
                continue
   
if __name__=="__main__":
    if not len(sys.argv)==3:
        print "username and password"
        sys.exit(1)
    user=sys.argv[1]
    pwd=sys.argv[2]
    os.system('cls')
    print monitor(user,pwd)
   
   
   

原文地址:https://www.cnblogs.com/macula7/p/1960557.html