#!/usr/bin/env python #coding:utf-8 import MySQLdb,requests import time from datetime import datetime global sendtime global flag global monitor_time number = 0 to_email = [] params = {} timedic = {} a=[] b=[] c=[] def sendmail(mail_list, message): url = "http://api.sendcloud.net/apiv2/mail/send" for number in range(len(mail_list)): params['apiUser'] = "" params['apiKey'] = "" params['from'] = "" params['fromName'] = "bill" params['subject'] = "warning" params['html'] = "your html is abnormal: " + message params['to'] = mail_list[number] r = requests.post(url, files={}, data=params) print r.text #get请求 def get_status(url): g = requests.get(url,allow_redirects = False) return g.status_code,g.content #post请求 def post_status(url): p = requests.post(url,allow_redirects = False) return p.status_code , p.content if __name__ == '__main__': while True: conn = MySQLdb.connect(host='127.0.0.1', user='root', passwd='734815', db='url_monitor') cur = conn.cursor() # 查找所有的 reCount = cur.execute('select * from url_test;') # 获取所有的url及相关参数 all_urls = cur.fetchall() for item in all_urls: #设置初始值 if number == 0: timedic[item[0]] = 0 flag = 0 #监控间隔 monitor_time = int(item[5]) #判断是post还是get请求 if item[1] == 'get': current_status = get_status(item[0]) else: current_status = post_status(item[0]) to_email = item[3].split(',') #print to_email a = [] b = [] c = [] #此时存在数据库与直接获取的页面都存在空白符,所以需要去掉,用函数去出现问题 #数据库 for n in range(len(item[4])): if item[4][n] != ' ' : a.append(item[4][n]) for n in range(len(a)): if a[n] != ' ': c.append(a[n]) #直接获取 for n in range(len(current_status[1])): if current_status[1][n] != ' ': b.append(current_status[1][n]) #请求之后的状态跟预设的状态不一致,或者请求的页面与预设的页面不一致 if current_status[0] != int(item[2]) or c != b: #异常发送 if timedic[item[0]] == 0: # 标志着此时的状态是不正常的 flag = 1 sendtime = datetime.now() timedic[item[0]] = 1 message = item[0] + ' ' + str(current_status[0]) + ' is mismatch with preset! ' + 'The preset is ' + str(item[2])+'or the reponse is error' sendmail(to_email, message) #print message currenttime = datetime.now() if (currenttime-sendtime).seconds >= 3: timedic[item[0]] = 0 #如果此时恢复正常 if current_status[0] == int(item[2]) and c == b: if flag == 1: message = item[0] + ' Change from abnomaly to normal!' sendmail(to_email, message) flag = 0 #print message else: print item[0]+' is normal!' # 正常状态 number = 1 # 控制监控的间隔,有数据库的监控间隔决定 time.sleep(monitor_time) cur.close() conn.close()