由于自己是负责海外项目,常常会遇到一些问题,最近被系统时间与mysql时间不在一个时区,而坑了自己,一般修改了系统时区之后,MySQL必须重启,不然MySQL时区是不对的,会导致数据全部都是错的~~~,哎,只有坑到了自己,才会想到要去避免这种事情再次出现,所以用python写了一个简单判断时区的脚本,时区不对并邮件发出来,大家参考参考,详情如下:
1、脚本实例#!/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) 2、测试结果
|