zoukankan      html  css  js  c++  java
  • Nagios 调用华为云短信平台进行报警

    1.创建 /usr/local/nagios/script/hwc_sms.py

    """
    @author:
    @contact:
    @version:
    """
    
    # -*- coding: utf-8 -*-
    import time
    import uuid
    import hashlib
    import base64
    import requests  # 需要先使用pip install requests命令安装依赖
    import sys
    import urllib3
    
    # 日志处理
    
    
    # 必填,请参考"开发准备"获取如下数据,替换为实际值
    url = 'https://rtcsms.cn-north-1.myhuaweicloud.com:10743/sms/batchSendSms/v1'  # APP接入地址+接口访问URI
    APP_KEY = ""  # APP_Key
    APP_SECRET = ""  # APP_Secret
    sender = ""  # 国内短信签名通道号或国际/港澳台短信通道号
    TEMPLATE_ID = ""  # 模板ID
    
    # 条件必填,国内短信关注,当templateId指定的模板类型为通用模板时生效且必填,必须是已审核通过的,与模板类型一致的签名名称
    # 国际/港澳台短信不用关注该参数
    signature = "华为云短信测试"  # 签名名称
    
    # 必填,全局号码格式(包含国家码),示例:+8615123456789,多个号码之间用英文逗号分隔
    # receiver = "+8615123456789"  # 短信接收人号码
    
    
    # 选填,短信状态报告接收地址,推荐使用域名,为空或者不填表示不接收状态报告
    statusCallBack = ""
    
    '''
    选填,使用无变量模板时请赋空值 TEMPLATE_PARAM = '';
    单变量模板示例:模板内容为"您的验证码是${1}"时,TEMPLATE_PARAM可填写为'["369751"]'
    双变量模板示例:模板内容为"您有${1}件快递请到${2}领取"时,TEMPLATE_PARAM可填写为'["3","人民公园正门"]'
    模板中的每个变量都必须赋值,且取值不能为空
    查看更多模板和变量规范:产品介绍>模板和变量规范
    
    
    输入参数
    用例:python hwc_sms.py ServiceName Hostname WarningState WarningNote
    '''
    
    receiver = str(sys.argv[1]).replace(".", "_").replace("-", "_")
    ServiceName = str(sys.argv[2]).replace(".", "").replace("-", "").replace("_", "").replace("Service", "")
    HostName = str(sys.argv[3]).replace(".", "-").replace("-", "_")
    WarningState = str(sys.argv[4]).replace(".", "_").replace("-", "_")
    ReportTime = time.strftime("%H:%M:%S").replace(".", "_")
    WarningNotes = str(sys.argv[5]).replace(".", "_").replace("-", "_")[0:14]
    
    TEMPLATE_PARAM = []
    
    TEMPLATE_PARAM.append(ServiceName)
    TEMPLATE_PARAM.append(HostName)
    TEMPLATE_PARAM.append(WarningState)
    TEMPLATE_PARAM.append(ReportTime)
    TEMPLATE_PARAM.append(WarningNotes)
    
    TEMPLATE_PARAM = str(TEMPLATE_PARAM)
    
    
    
    
    '''
    构造X-WSSE参数值
    @param appKey: string
    @param appSecret: string
    @return: string
    '''
    
    
    def buildWSSEHeader(appKey, appSecret):
        now = time.strftime('%Y-%m-%dT%H:%M:%SZ')  # Created
        nonce = str(uuid.uuid4()).replace('-', '')  # Nonce
        print(nonce)
        digest = hashlib.sha256((nonce + now + appSecret).encode()).hexdigest()
    
        digestBase64 = base64.b64encode(digest.encode()).decode()  # PasswordDigest
        return 'UsernameToken Username="{}",PasswordDigest="{}",Nonce="{}",Created="{}"'.format(appKey, digestBase64, nonce,
                                                                                                now);
    
    
    def main():
        # 请求Headers
        header = {'Authorization': 'WSSE realm="SDP",profile="UsernameToken",type="Appkey"',
                  'X-WSSE': buildWSSEHeader(APP_KEY, APP_SECRET)}
        # 请求Body
        formData = {'from': sender,
                    'to': receiver,
                    'templateId': TEMPLATE_ID,
                    'templateParas': TEMPLATE_PARAM,
                    'statusCallback': statusCallBack,
                    #                'signature': signature #使用国内短信通用模板时,必须填写签名名称
                    }
        print(header)
        print(TEMPLATE_PARAM)
        requests.packages.urllib3.disable_warnings()
    
        # 为防止因HTTPS证书认证失败造成API调用失败,需要先忽略证书信任问题
        r = requests.post(url, data=formData, headers=header, verify=False)
        print(r.text)  # 打印响应信息
    
    
    # def console_out(logFilename):
        # ''''' Output log to file and console '''
        # # Define a Handler and set a format which output to file
        # logging.basicConfig(
        #     level=logging.DEBUG,  # 定义输出到文件的log级别,大于此级别的都被输出
        #     format='%(asctime)s %(filename)s : %(levelname)s %(message)s',  # 定义输出log的格式
        #     datefmt='%Y-%m-%d %A %H:%M:%S',  # 时间
        #     filename=logFilename,  # log文件名
        #     filemode='w')  # 写入模式“w”或“a”
        # # Define a Handler and set a format which output to console
        # console = logging.StreamHandler()  # 定义console handler
        # console.setLevel(logging.INFO)  # 定义该handler级别
        # formatter = logging.Formatter('%(asctime)s %(filename)s : %(levelname)s %(message)s')  # 定义该handler格式
        # console.setFormatter(formatter)
        # # Create an instance
        # logging.getLogger().addHandler(console)  # 实例化添加handler
        #
        # # Print information       # 输出日志级别
        # logging.debug('logger debug message')
        # logging.info('logger info message')
        # logging.warning('logger warning message')
        # logging.error('logger error message')
        # logging.critical('logger critical message')
    
    
    if __name__ == '__main__':
    
        # filename = 'recode.log'
        sys.stdout = open('recode.log', mode='a', encoding='utf-8')
        main()
    hwc_sms.py

    //华为云字符长度、特殊符号限制比较严重,需要注意

    2. 在command.cfg中增加短信报警命令

    # 'notify-by-sms' command definition
    define command{
            command_name    notify-by-sms
            command_line    /usr/local/python3/bin/python3 /usr/local/nagios/script/hwc_sms.py $CONTACTPAGER$ "$SERVICEDESC$" "$NOTIFICATIONTYPE$" "$SERVICEST
    ATE$" "$SERVICEOUTPUT$"
            }

    3. 在contacts.cfg中,对需要接受短信的用户添加

    service_notification_commands notify-by-sms
    host_notification_commands notify-by-sms

    4. 重启nagios服务

  • 相关阅读:
    Day10
    Day9
    Day8
    Day 7
    Day-6
    java中的原子性
    java 原子性
    内存可见性
    JVM 常忘笔记
    JVM 解释执行 编译执行 JIT
  • 原文地址:https://www.cnblogs.com/bionexit/p/13354516.html
Copyright © 2011-2022 走看看