zabbix--微信告警

zabbix 微信告警機制

zabbix 告警機制有不少,好比郵件、微信、電話、短信等等。不少,可是像電話和短信都是有錢人玩的,咱們這些窮屌絲玩玩 微信 郵件 就能夠了。php

參考:https://github.com/X-Mars/Zabbix-Alert-WeChathtml

微信告警首先得註冊一個企業微信,而後才能實現微信告警。註冊地址:https://work.weixin.qq.com/python

實戰

註冊企業微信git

註冊成功後,進入後臺管理github

添加一個部門,並記住部門 IDweb

添加一個用戶到上面建立的部門裏面(這裏採起直接將管理員添加進去)json

建立一個自建應用bootstrap

建立完成記住 AgentID  和 Secretvim

記住企業 IDapi

到這裏上面的企業微信註冊就完成了,記住上面所提到須要記住的。

zabbix-server 配置

1)編輯zabbix-server 配置文件進行配置(我這裏是源碼安裝的,路徑爲/usr/local/zabbix;若是是yum安裝的,路徑爲/etc/zabbix/)

# vim /usr/local/zabbix/etc/zabbix_server.conf
AlertScriptsPath=/usr/local/zabbix/lib/zabbix/alertscripts     //(若是不存在則自動建立)
# mkdir -p /usr/local/zabbix/lib/zabbix/alertscripts

2)安裝組件 requests

  • 方法一
    # pip install requests
    # pip install --upgrade requests
  • 方法二
    # wget https://pypi.python.org/packages/c3/38/d95ddb6cc8558930600be088e174a2152261a1e0708a18bf91b5b8c90b22/requests-2.18.3.tar.gz
    # tar zxvf requests-2.18.3.tar.gz
    # cd requests-2.18.3
    # python setup.py build
    # python setup.py install 

4)下載安裝腳本

# git clone https://github.com/X-Mars/Zabbix-Alert-WeChat.git
# cp Zabbix-Alert-WeChat/wechat.py /usr/local/zabbix/lib/zabbix/alertscripts/    //copy到上面配置文件配置的目錄下
# chmod +x /usr/local/zabbix/lib/zabbix/alertscripts/wechat.py

下載下來後腳本的內容

#!/usr/bin/python2.7
#_*_coding:utf-8 _*_
#auther:火星小劉

import requests,sys,json
import urllib3
urllib3.disable_warnings()

reload(sys)
sys.setdefaultencoding('utf-8')

def GetTokenFromServer(Corpid,Secret):
    Url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken"
    Data = {
        "corpid":Corpid,
        "corpsecret":Secret
    }
    r = requests.get(url=Url,params=Data,verify=False)
    print(r.json())
    if r.json()['errcode'] != 0:
        return False
    else:
        Token = r.json()['access_token']
        file = open('/tmp/zabbix_wechat_config.json', 'w')
        file.write(r.text)
        file.close()
        return Token

def SendMessage(User,Agentid,Subject,Content):
    try:
        file = open('/tmp/zabbix_wechat_config.json', 'r')
        Token = json.load(file)['access_token']
        file.close()
    except:
        Token = GetTokenFromServer(Corpid, Secret)

    n = 0
    Url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=%s" % Token
    Data = {
        "touser": User,                                 # 企業號中的用戶賬號,在zabbix用戶Media中配置,若是配置不正常,將按部門發送。
        #"totag": Tagid,                                # 企業號中的標籤id,羣發使用(推薦)
        #"toparty": Partyid,                            # 企業號中的部門id,羣發時使用。
        "msgtype": "text",                              # 消息類型。
        "agentid": Agentid,                             # 企業號中的應用id。
        "text": {
            "content": Subject + '\n' + Content
        },
        "safe": "0"
    }
    r = requests.post(url=Url,data=json.dumps(Data),verify=False)
    while r.json()['errcode'] != 0 and n < 4:
        n+=1
        Token = GetTokenFromServer(Corpid, Secret)
        if Token:
            Url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=%s" % Token
            r = requests.post(url=Url,data=json.dumps(Data),verify=False)
            print(r.json())

    return r.json()


if __name__ == '__main__':
    User = sys.argv[1]                                                                # zabbix傳過來的第一個參數
    Subject = str(sys.argv[2])                                                        # zabbix傳過來的第二個參數
    Content = str(sys.argv[3])                                                        # zabbix傳過來的第三個參數

    Corpid = "wxaf"                                                                     # CorpID是企業號的標識
    Secret = "aKDdCRT76"                                                                # Secret是管理組憑證密鑰
    #Tagid = "1"                                                                        # 通信錄標籤ID
    Agentid = "1000001"                                                                 # 應用ID
    #Partyid = "1"                                                                      # 部門ID

    Status = SendMessage(User,Agentid,Subject,Content)
    print Status
下載完成時的腳本內容

5)根據腳本里面的註釋進行相應的修改,改爲本身企業微信號中的信息。以下

#!/usr/bin/python2.7
#_*_coding:utf-8 _*_
#auther:火星小劉

import requests,sys,json
import urllib3
urllib3.disable_warnings()

reload(sys)
sys.setdefaultencoding('utf-8')

def GetTokenFromServer(Corpid,Secret):
    Url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken"
    Data = {
        "corpid":Corpid,
        "corpsecret":Secret
    }
    r = requests.get(url=Url,params=Data,verify=False)
    print(r.json())
    if r.json()['errcode'] != 0:
        return False
    else:
        Token = r.json()['access_token']
        file = open('/tmp/zabbix_wechat_config.json', 'w')
        file.write(r.text)
        file.close()
        return Token

def SendMessage(User,Agentid,Subject,Content):
    try:
        file = open('/tmp/zabbix_wechat_config.json', 'r')
        Token = json.load(file)['access_token']
        file.close()
    except:
        Token = GetTokenFromServer(Corpid, Secret)

    n = 0
    Url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=%s" % Token
    Data = {
        "touser": "LiYanJie",                           # 企業號中的用戶賬號,在zabbix用戶Media中配置,若是配置不正常,將按部門發送。
        #"totag": Tagid,                                # 企業號中的標籤id,羣發使用(推薦)
        "toparty": 2,                                   # 企業號中的部門id,羣發時使用。
        "msgtype": "text",                              # 消息類型。
        "agentid": 1000002,                             # 企業號中的應用id。
        "text": {
            "content": Subject + '\n' + Content
        },
        "safe": "0"
    }
    r = requests.post(url=Url,data=json.dumps(Data, ensure_ascii=False),verify=False)
    while r.json()['errcode'] != 0 and n < 4:
        n+=1
        Token = GetTokenFromServer(Corpid, Secret)
        if Token:
            Url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=%s" % Token
            r = requests.post(url=Url,data=json.dumps(Data, ensure_ascii=False),verify=False)
            print(r.json())

    return r.json()


if __name__ == '__main__':
    User = sys.argv[1]                                                                # zabbix傳過來的第一個參數
    Subject = str(sys.argv[2])                                                        # zabbix傳過來的第二個參數
    Content = str(sys.argv[3])                                                        # zabbix傳過來的第三個參數

    Corpid = "ww986f52f27xxxxxxx"                                                     # CorpID是企業號的標識
    Secret = "Sinht6K7VBaJmjuZDaoOnCoyovcLHxxxxxxxxxxxxxx"                            # Secret是管理組憑證密鑰
    #Tagid = "1"                                                                      # 通信錄標籤ID
    Agentid = "1000002"                                                               # 應用ID
    Partyid = "2"                                                                     # 部門ID

    Status = SendMessage(User,Agentid,Subject,Content)
    print Status

6)測試腳本是否可用

# python /usr/local/zabbix/lib/zabbix/alertscripts/wechat.py www web 123
{u'invaliduser': u'', u'errcode': 0, u'errmsg': u'ok'}

補充說明:腳本里面默認是python2.7  而咱們系統自帶的是python2.6 那麼須要安裝python2.7。安裝參考

# python -V
Python 2.6.6

//下載軟件包
# wget https://www.python.org/ftp/python/2.7.6/Python-2.7.6.tgz

//解壓軟件包
# tar xvf Python-2.7.6.tgz

//進入解壓目錄
# cd Python-2.7.6

//安裝
# ./configure --prefix=/usr/local/
# make && make install

//查看安裝完成的版本
# /usr/local/bin/python2.7 -V

//建立快捷啓動命令
# cp /usr/local/bin/python2.7 /usr/bin/python2.7
# mv /usr/bin/python /usr/bin/python2.6.6
# ln -s /usr/local/bin/python2.7 /usr/bin/python

//查看版本
# python -V

//下載和安裝bootstrap工具包和pip工具包
# wget https://bootstrap.pypa.io/ez_setup.py -O - | python
# wget https://pypi.python.org/packages/11/b6/abcb525026a4be042b486df43905d6893fb04f05aac21c32c638e939e447/pip-9.0.1.tar.gz#md5=35f01da33009719497f01a4ba69d63c9
# tar xvzf pip-9.0.1.tar.gz
# cd pip-9.0.1
# python setup.py install
# rm -rf /usr/bin/pip
# cp /usr/local/bin/pip /usr/bin/pip
# pip install --upgrade pip
python2.6升級到python2.7

server 端Web界面配置 

進入:配置 -> 報警媒介類型 -> 建立媒體類型

腳本參數

{ALERT.SENDTO}
{ALERT.SUBJECT}
{ALERT.MESSAGE}

給用戶添加報警媒介,也能夠新建一個用戶用來專門來用於微信報警,我這裏直接使用 admin 用戶了(說明:這裏收件人對應企業微信號中的應用ID

測試

停掉被監控主機上面的應用,看可否發送微信消息

# /etc/init.d/php-fpm stop
Stopping php-fpm:                                          [  OK  ]

能夠看到能夠收到微信消息,至此,微信告警就搞定了。

文中自動重啓php-fpm的操做參考:http://www.javashuo.com/article/p-mvzvvhdf-d.html

文中消息內容更改自定義參考:http://www.javashuo.com/article/p-ghslqzqk-u.html

郵件告警:http://www.javashuo.com/article/p-ycshfagw-cw.html

釘釘告警:http://www.javashuo.com/article/p-zwffpgzq-cd.html

相關文章
相關標籤/搜索