#coding:utf-8
import MySQLdb
import urllib2
import urllib
import codecs
import time
import datetime
import ConfigParser
import os
import socket
abs_path = os.path.abspath(os.path.dirname(__file__))
nms_dir = os.path.dirname(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
base_configure = os.path.join(nms_dir,'configure/base_configure')
def read_configure(filename, key, value):##取值函数,从文件中取值,共三个参数(文件名,键,键值)
cf = ConfigParser.ConfigParser()
cf.read(filename)
value_list = cf.get(key, value)
return value_list
connect = read_configure(base_configure,'monitor_mess','phone_number')##信息报警联系方式
dbhost1 = read_configure(base_configure,'mysql_gj','dbhost1')
dbhost2 = read_configure(base_configure,'mysql_gj','dbhost2')
sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sk.settimeout(1)
try:##异常嵌套
try:##测试主数据库是否开放
sk.connect((dbhost1,3306))
dbhost = dbhost1
except Exception:##若主数据库不开放则设置主机为从数据库,然后登录从库,若能登录说明从库正常,继续执行代码,若从库down则抛出异常
dbhost = dbhost2
sk.close()
now_time=datetime.datetime.now()
last = ((now_time+datetime.timedelta(minutes=-1)).strftime("%Y-%m-%d %H:%M:%S"))
con=MySQLdb.connect(host=dbhost,user="gj",passwd="xbrother",db="historyver1",charset="utf8")
cur = con.cursor()
cur.execute("select device_id,descr,event_time,event_level,is_confirm FROM t_event where event_level >= '4' and event_time > %s", last)
alldata = cur.fetchall()
if alldata== ():
time.sleep(10)
else:
alldata = list(alldata)
for sql_info in alldata:
warn_id = sql_info[0].encode("gbk")
warn_msg = sql_info[1].encode("gbk")
warn_time = sql_info[2].strftime('%Y-%m-%d %H:%M:%S').encode("gbk")
warn_level = str(sql_info[3]).encode("gbk")
if sql_info[4] == 0:
warn_ack = u'是'
else:
warn_ack = u'否'
warn_ack = warn_ack.encode('gbk')
message = u"事件地址:".encode("gbk")+warn_id+'_'+u"事件内容:".encode("gbk")+warn_msg+'_'+u"事件时间:".encode("gbk")+warn_time+'_'+u"事件等级:".encode("gbk")+warn_level+'_'+u"是否确认:".encode("gbk")+warn_ack
url = "http://sendsms.10jqka.com.cn/qxt/newsendsms.php?method=1&mobile=%s&content=%s&via=baiwu&mtype=99" %(connect, message)
html = urllib2.urlopen(url)##短信报警
cur.close()
con.close()
except Exception:##从库异常,抛出异常,主备数据库都不可用,数据库异常
message = u"主备数据库都不可用,请及时处理".encode("gbk")
url = "http://sendsms.10jqka.com.cn/qxt/newsendsms.php?method=1&mobile=%s&content=%s&via=baiwu&mtype=99" %(connect, message)
html = urllib2.urlopen(url)
然后使用crontab命令执行文件,一分钟执行一次脚本。
[root@ap_15_6 configure]# cat /etc/crontab##每分钟执行一次脚本
*/1 * * * * root python2.6 /opt/hxnms/scripts/system_monitor/warn.py3 >/dev/null 2>&1