python数据库查询监控

#!/usr/bin/python2.7
# encoding: utf-8

#import MySQLdb as MySQLdb
import MySQLdb
import traceback
import time
import smtplib
from email.mime.text import MIMEText

def getCurrentDateTime():
now=int(time.time())
timeArray=time.localtime(now)
todayDate=time.strftime("%Y-%m-%d",timeArray)
todayTime=time.strftime("%H:%M:%S",timeArray)
todayDateTime=time.strftime("%Y-%m-%d %H:%M:%S",timeArray)
return todayDateTime

def sendMail(tomail,subject,body):
HOST="aaa.123.com"
SUBJECT=subject
TO=tomail
FROM="[email protected]"
text=body

msg=MIMEText(text,"plain","utf-8")
msg['Subject'] = SUBJECT
msg['From'] = FROM
msg['To'] = ','.join(TO)

try:
server=smtplib.SMTP()
server.connect(HOST,"25")
server.starttls()
server.login("[email protected]","bbbbbb")
server.sendmail(FROM,TO,msg.as_string())
server.quit()
print "邮件发送成功"
except Exception,e:
print "失败"+str(e)

def connRemoteMysql(*arg):

ip = arg[0]
user = arg[1]
passwd = arg[2]
port = arg[3]

try:
conn = MySQLdb.connect(host=ip,user=user,passwd=passwd,port=port,charset='utf8') #关键字参数
#cursor = conn.cursor(cursorclass=MySQLdb.cursors.DictCursor) #传递参数cursors.DictCursor返回字典结构
cursor = conn.cursor() #获取操作游标
conn.select_db('aaa') #得到当前指向数据库的指针
#sql1 = 'select * from aaa_user ;'
sql2 = 'select count(*) from bbb_user;'
cursor.execute(sql2) #执行命令方法
tuple1 = cursor.fetchall() #接收返回值方法
tuple2 = tuple1[0]
result = tuple2[0]
#print "当前注册用户数为:%s" % r #内置%格式化字符串,
#print "aaaa:{num}人。".format(num=result) #str.format()字符串处理函数
#conn.commit()
return result
except:
traceback.print_exc()
conn.rollback()
finally:
cursor.close()
conn.close()
if __name__ == "__main__":

ip = "192.168.11.1"
user = "aaa"
passwd = "bbbbb"
port = 3306
person = connRemoteMysql(ip,user,passwd,port)

tomail = ['[email protected]']
body = "aaa:{}".format(person)
subject = "aaa-%s" % getCurrentDateTime()
sendMail(tomail, subject, body)

你可能感兴趣的:(python数据库查询监控)