服务器监控脚本 发表于 2019-04-09 | 分类于 Python | monitor.py 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778# coding:utf-8# !/usr/bin/env python3import osimport timefrom aliyunsdkdysmsapi.request.v20170525 import SendSmsRequestfrom aliyunsdkdysmsapi.request.v20170525 import QuerySendDetailsRequestfrom aliyunsdkcore.client import AcsClientimport uuidfrom aliyunsdkcore.profile import region_providerfrom aliyunsdkcore.http import method_type as MTfrom aliyunsdkcore.http import format_type as FTimport const# from config import Alarm_cachefrom config import Settings# 监控逻辑# 注意:不要更改REGION = "cn-hangzhou"PRODUCT_NAME = "Dysmsapi"DOMAIN = "dysmsapi.aliyuncs.com"acs_client = AcsClient(const.ACCESS_KEY_ID, const.ACCESS_KEY_SECRET, REGION)region_provider.add_endpoint(PRODUCT_NAME, REGION, DOMAIN)def send_sms(phone_numbers, sign_name, template_code, template_param=None): smsRequest = SendSmsRequest.SendSmsRequest() # 申请的短信模板编码,必填 smsRequest.set_TemplateCode(template_code) # 短信模板变量参数 if template_param is not None: smsRequest.set_TemplateParam(template_param) # 短信签名 smsRequest.set_SignName(sign_name) # 数据提交方式 # smsRequest.set_method(MT.POST) # 数据提交格式 # smsRequest.set_accept_format(FT.JSON) # 短信发送的号码列表,必填。 smsRequest.set_PhoneNumbers(phone_numbers) # 调用短信发送接口,返回json smsResponse = acs_client.do_action_with_exception(smsRequest) # TODO 业务处理 return smsResponsedef monitor(): print('***启动监控***') while True: ports = [8000, 8001, 8002] for port in ports: check_url = "http://api.XXX.cn:%s/server?type=0" % ( port) command = "curl -I -m 30 -o /dev/null -s -w %{http_code} " + check_url http_code = os.popen(command).read() print("ping %s 状态码为%s" % (check_url, http_code)) if http_code != "200": # Alarm_cache["ping_error"].append(diff) # 发短信 print("###发送短信给相关的人###") params = "{\"interface\":\"%s\"}" % (port) for phone in Settings["alarm_phones"]: print(send_sms(phone, "thisissignname", "SMS_99999999", params)) time.sleep(300) print('5分钟后检查')if __name__ == '__main__': monitor() config.py 12345678# coding:utf-8Alarm_cache = { "ping_error": []}# 配置Settings = { "alarm_phones": ['thisiscellphone']}