本文共 1914 字,大约阅读时间需要 6 分钟。
定时对网站/API进行请求,根据请求响应判断服务是否可用,网站是否存在宕机,当发生宕机时,发送短信通知管理员.
运行平台:阿里云函数计算
开发语言:Python3(小功能,精简,开发快,可在阿里云上在线编辑代码)其它:阿里云短信接口为何选用函数计算?
httpchk
httpchk-trigger
-时间间隔1分钟函数代码:
# -*- coding: utf-8 -*-import loggingimport requestsfrom aliyunsdkcore.client import AcsClientfrom aliyunsdkcore.request import CommonRequest# 待检测的网址,仅支持GET请求urls = ["https://www.baidu.com","http://www.mtain.top"]# 接收短信通知的手机号码phone = "180000000"# 阿里云短信接口相关信息accessKeyId = 'xxxx'accessSecret = 'xxxx'signName = 'xxxxx'templateCode = 'SMS_xxxx'logger = logging.getLogger()def handler(event, context): for url in urls: do_httpchk(url)def do_httpchk(url): logger.info('检测网站:{}'.format(url)) try: req=requests.get(url) logger.info('网站:{}响应正常,返回数据长度:{}'.format(url,len(req.text))) except Exception as e: logger.error('网站:{}服务异常,{}'.format(url,e)) send_sms(url) def send_sms(url): client = AcsClient(accessKeyId, accessSecret, 'default') request = CommonRequest() request.set_accept_format('json') request.set_domain('dysmsapi.aliyuncs.com') request.set_method('POST') request.set_protocol_type('https') # https | http request.set_version('2017-05-25') request.set_action_name('SendSms') request.add_query_param('PhoneNumbers', phone) request.add_query_param('SignName', signName) request.add_query_param('TemplateCode', templateCode) # 阿里云短信变量 [a-zA-Z0-9] 且 长度小于20 web_name = url.replace('https://','').replace('http://','').replace('.','-')[0:18] request.add_query_param('TemplateParam', '{"code":"'+web_name+'"}') response = client.do_action(request) logger.info('Send SMS Response:'+str(response, encoding = 'utf-8'))
转载地址:http://ladxl.baihongyu.com/