因爲本身是負責海外項目,經常會遇到一些問題,最近被系統時間與mysql時間不在一個時區,而坑了本身,通常修改了系統時區以後,MySQL必須重啓,否則MySQL時區是不對的,會致使數據所有都是錯的~~~,哎,只有坑到了本身,纔會想到要去避免這種事情再次出現,因此用python寫了一個簡單判斷時區的腳本,時區不對並郵件發出來,你們參考參考,詳情以下:html
一、腳本實例python
#!/usr/bin/env python # coding=utf8 # auther:kuangl # This is system time and sql time diff from datetime import * import os,sys,socket,fcntl,struct import MySQLdb import smtplib from email.mime.multipart import MIMEMultipart from email.mime.base import MIMEBase from email.mime.text import MIMEText reload(sys) sys.setdefaultencoding('utf8') '''定義發送郵件函數''' def sendmail(html,emailaddress,mailSubject,from_address="monitor@test.com"): mail_list=emailaddress.split(",") msg=MIMEMultipart() msg['Accept-Language']='zh-CN' msg['Accept-Charset']= 'ISO-8859-1,utf-8' msg['From']=from_address msg['to']=";".join(mail_list) msg['Subject']=mailSubject.decode("utf-8") txt=MIMEText(html,'html','utf-8') txt.set_charset('utf-8') msg.attach(txt) smtp=smtplib.SMTP("mail.test.com") smtp.sendmail(msg["From"],mail_list,msg.as_string()) smtp.close() '''查看本機hostname''' hostname=socket.gethostname() print hostname '''查看本機IP地址''' def get_ip_address(ifname): s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) return socket.inet_ntoa(fcntl.ioctl( s.fileno(), 0x8915, struct.pack('256s',ifname[:15]) )[20:24]) ip_add = get_ip_address('eth0') print ip_add '''查看系統時間''' nowtime = datetime.now() daytime = nowtime.strftime('%Y-%m-%d %H:%M') print 'system time time:', daytime '''查看數據庫時間''' pwd='111133334444' SQL='select now()' def mysql_connect(sql,host): try: conn=MySQLdb.connect(host='127.0.0.1',user='rd',passwd=pwd,port=3306) cur=conn.cursor() cur.execute(sql) result=cur.fetchall() cur.close() conn.close() return result except MySQLdb.Error,e: print "Mysql Error %d: %s" % (e.args[0],e.args[1]) server_result=mysql_connect(sql=SQL,host='127.0.0.1') sql_gettime=server_result[0][0] SQLTime=sql_gettime.strftime('%Y-%m-%d %H:%M') print 'SQL server time:',SQLTime ''' 定義郵件參數''' Content= 'Dear ALL: <br> ' + ip_add + ' , System and Database time error, <br> System time is : '+ daytime +' <br> Database time is : ' + SQLTime + ' <br> Please check all time! <br> <br> Friendly reminder,Please note!' Subject= '[監控][海外時區監控][' + hostname + ']System and Database time error' ''' 判斷時間是否相等''' if daytime == SQLTime: print "system and sql time is OK, not sednemail" else: print "system and sql time is Fail,Start email to all" sendmail(html=Content,emailaddress='kuangling@test.com',mailSubject=Subject)
二、測試結果
mysql