服务器监控脚本

monitor.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# coding:utf-8
# !/usr/bin/env python3
import os
import time
from aliyunsdkdysmsapi.request.v20170525 import SendSmsRequest
from aliyunsdkdysmsapi.request.v20170525 import QuerySendDetailsRequest
from aliyunsdkcore.client import AcsClient
import uuid
from aliyunsdkcore.profile import region_provider
from aliyunsdkcore.http import method_type as MT
from aliyunsdkcore.http import format_type as FT
import const
# from config import Alarm_cache
from 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 smsResponse
def 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

1
2
3
4
5
6
7
8
# coding:utf-8
Alarm_cache = {
"ping_error": []
}
# 配置
Settings = {
"alarm_phones": ['thisiscellphone']
}