您的位置:首页 > 编程语言 > Python开发

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

2010-01-05 23:36 309 查看
原理很简单,定期连接数据库,如果出现错误,发送邮件到指定邮箱中。

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)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: