zabbix報警指令碼(wechat,email)

禁止進入i發表於2019-02-16

微信報警

#!/usr/bin/python
# -- coding:utf-8 --
"""
參考文件:
        1、https://work.weixin.qq.com/api/doc#10013/%E7%AC%AC%E4%B8%89%E6%AD%A5%EF%BC%9A%E8%8E%B7%E5%8F%96access_token
        2、https://work.weixin.qq.com/api/doc#10167/%E6%96%87%E6%9C%AC%E6%B6%88%E6%81%AF
"""
import requests
import json
import sys

class Wechat():
    def __init__(self,corpid,corpsecret):
        self.url = "https://qyapi.weixin.qq.com/cgi-bin/"
        self.corpid = corpid
        self.corpsecret = corpsecret
    #獲取access_token
    def get_token(self):
        token = "{url}gettoken?corpid={corpid}&corpsecret={corpsecret}".format(url=self.url,corpid=self.corpid,corpsecret=self.corpsecret)
        json_data =  json.loads(requests.get(token).content.decode())
        access_token = json_data["access_token"]
        return access_token
    #獲取傳送訊息
    def send_message(self,user,agentid,subject,content):
        send_url = "{url}message/send?access_token={access_token}".format(url=self.url,access_token=self.get_token())
        data = {
            "touser": user,
            "toparty": "2",    #獲取使用者失敗會將訊息傳送給部門的人,可以檢視部門id修改,多個部門用|分割
            "msgtype": "text",
            "agentid":agentid ,
            "text": {
                "content": subject + `
` + content
            },
             "safe":0

        }
        #傳送報警訊息
        requests.post(send_url,json.dumps(data))

if __name__ == `__main__`:
    #abbix傳過來的第一個引數
    user = sys.argv[1]
    #zabbix傳過來的第二個引數
    subject = str(sys.argv[2])
    #zabbix傳過來的第三個引數
    content = str(sys.argv[3])
    #呼叫Wechat類,繫結企業微信的id和應用的Secret
    wechat = Wechat("ww3f7e13339beb9a1d","fWN9iyF9X8vEETLi7xgjRZ40g3vOT-NA18lvCe93EdI")
    #呼叫例項化的類的傳送資訊功能,其中agentid等於自建應用的AgentId
    wechat.send_message(user,1000002,subject,content)

郵件報警

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import smtplib
from email.mime.text import MIMEText
class Memcache_Monitor():
    def __init__(self):
        pass
    def send_mail(self,to_list, subject, content):
        # 郵件地址的smtp地址
        mail_host = `smtp.exmail.qq.com`
        # 用來發郵件的郵箱
        mail_user = `xxxxxx`
        # 郵箱的密碼
        mail_pass = `xxxxx`
        # smtp地址的主網站地址
        mail_postfix = `exmail.qq.com`
        sender = "{name}<{name}@{postfix}".format(name=mail_user, postfix=mail_postfix)
        msg = MIMEText(content, `plain`, `utf-8`)
        # 必須使用`utf-8`引數,解決在部分郵件客戶端中文會顯示為亂碼
        msg[`Subject`] = subject
        msg[`From`] = sender
        msg[`to`] = to_list
        try:
            smtpobj = smtplib.SMTP()
            smtpobj.connect(mail_host)
            smtpobj.login(mail_user, mail_pass)
            smtpobj.sendmail(sender, to_list, msg.as_string())
            smtpobj.close()
            print("傳送成功")
            return True
        except Exception as e:
            return False

相關文章