Cảnh báo qua mail cùng với check_mk cũng là một cách. Nhưng có nhiều người lại thích dùng với telegram. Ở bài này tôi sẽ hướng dẫn các bạn làm sao để có thể nhận cảnh báo của check_mk cùng với telegram

Đây là cảnh báo cùng với telegram. Bạn muốn cảnh báo cả với mail nữa không. Nếu có hãy tham khảo bài viết hướng dẫn cảnh báo check_mk cùng với gmail. Còn ở bài này chúng ta cùng tìm hiểu về cảnh báo qua telegram nhé

I. Tìm ID chat của telegram

1. Tạo bot chat

https://telegram.me/botfather
Vào link bên trên với trình duyệt để có thể tạo ra bot chat. Chọn open telegram

Đây là bot hướng dẫn và tạo một bot theo ý của chúng ta. Chọn newbot để tạo ra bot mới.

2. Mỗi bot đều có tên hãy đặt tên cho nó

3. Tiếp theo ta sẽ phải chọn ra một username cho bot này.

Username của bot phải được kết thúc bằng “bot”. Sau khi có được username hãy nhắn tin với bot đó nhé. Chúng ta hãy để ý token của HTTP API nhé sẽ phải dùng nó đấy

4. Chat với bot

Chúng ta có thể tìm nó với tên mà chúng ta đã đặt ở trên và rồi vào chat với nó
Các bạn chat gì cũng được nhé!

5. Tìm ID chat bằng HTTP API

Cú pháp

https://api.telegram.org/botToken/getUpdates

Các bạn hãy thay token tìm được ở bên trên của mình nhé

https://api.telegram.org/bot908652940:AAGYGskRFhRr42cy4or1FynDMtfKKzTIs6w/getUpdates
Sau đó chúng ta sẽ thấy được ID như vậy đó! hãy lưu trữ nó lại nhé!

II. Cấu hình trên checkmk

1.Tạo ra file telegram.py

vi /omd/sites/monitoring/share/check_mk/notifications/telegram.py

Nội dung file  telegram.py có cú pháp  như sau:

#!/usr/bin/env python
# Telegram V2

# Copyright Mathias Kettner  2013  mk@mathias-kettner.de
#           Stefan Gehn      2016  stefan+cmk@srcxbox.net

# check_mk is free software;  you can redistribute it and/or modify it
# under the  terms of the  GNU General Public License  as published by
# the Free Software Foundation in version 2.  check_mk is  distributed
# in the hope that it will be useful, but WITHOUT ANY WARRANTY;  with-
# out even the implied warranty of  MERCHANTABILITY  or  FITNESS FOR A
# PARTICULAR PURPOSE. See the  GNU General Public License for more de-
# ails.  You should have  received  a copy of the  GNU  General Public
# License along with GNU Make; see the file  COPYING.  If  not,  write
# to the Free Software Foundation, Inc., 51 Franklin St,  Fifth Floor,
# Boston, MA 02110-1301 USA.

# Telegram notification based on asciimail notification from
# check_mk 1.2.6p16.

import os
import re
import sys
reload(sys)
sys.setdefaultencoding('utf8')
import urllib
import urllib2
### CHANGE THESE ###
telegram_bot_token = 'TOKEN-HERE'
####################

tmpl_host_text = """*Check_MK: $HOSTNAME$ - $EVENT_TXT$*
```
Host:     $HOSTNAME$
Alias:    $HOSTALIAS$
Address:  $HOSTADDRESS$
Event:    $EVENT_TXT$
Output:   $HOSTOUTPUT$

$LONGHOSTOUTPUT$```"""

tmpl_service_text = """*Check_MK: $HOSTNAME$/$SERVICEDESC$ $EVENT_TXT$*
```
Host:     $HOSTNAME$
Alias:    $HOSTALIAS$
Address:  $HOSTADDRESS$
Service:  $SERVICEDESC$
Event:    $EVENT_TXT$
Output:   $SERVICEOUTPUT$

$LONGSERVICEOUTPUT$```"""

def substitute_context(template, context):
    # First replace all known variables
    for varname, value in context.items():
        template = template.replace('$'+varname+'$', value)

    # Remove the rest of the variables and make them empty
    template = re.sub("\$[A-Z_][A-Z_0-9]*\$", "", template)
    return template

def construct_message_text(context):
    notification_type = context["NOTIFICATIONTYPE"]
    if notification_type in [ "PROBLEM", "RECOVERY" ]:
        txt_info = "$PREVIOUS@HARDSHORTSTATE$ -> $@SHORTSTATE$"
    elif notification_type.startswith("FLAP"):
        if "START" in notification_type:
            txt_info = "Started Flapping"
        else:
            txt_info = "Stopped Flapping ($@SHORTSTATE$)"
    elif notification_type.startswith("DOWNTIME"):
        what = notification_type[8:].title()
        txt_info = "Downtime " + what + " ($@SHORTSTATE$)"
    elif notification_type == "ACKNOWLEDGEMENT":
        txt_info = "Acknowledged ($@SHORTSTATE$)"
    elif notification_type == "CUSTOM":
        txt_info = "Custom Notification ($@SHORTSTATE$)"
    else:
        txt_info = notification_type # Should neven happen

    txt_info = substitute_context(txt_info.replace("@", context["WHAT"]), context)

    context["EVENT_TXT"] = txt_info

    if context['WHAT'] == 'HOST':
        tmpl_text = tmpl_host_text
    else:
        tmpl_text = tmpl_service_text

    return substitute_context(tmpl_text, context)

def fetch_notification_context():
    context = {}
    for (var, value) in os.environ.items():
        if var.startswith("NOTIFY_"):
            context[var[7:]] = value.decode("utf-8")
    return context

def send_telegram_message(token, chat_id, text):
    url = 'https://api.telegram.org/bot%s/sendMessage' % (token)
    data = urllib.urlencode({'chat_id':chat_id, 'text':text, 'parse_mode':'Markdown'})
    #print("sending telegram message, url '%s', chat id '%s', text '%s'" % (url, chat_id, text))
    try:
        urllib2.urlopen(url, data).read()
    except urllib2.URLError, e:
        sys.stdout.write('Cannot send Telegram message: HTTP-Error %s %s\n' % (e.code, e))

def main():
    context = fetch_notification_context()
    telegram_chatid = context.get('CONTACT_TELEGRAM_CHAT_ID')
    if not telegram_chatid: # e.g. empty field in user database
        sys.stdout.write("Cannot send Telegram message: Empty destination chat id")
        sys.exit(2)
    text = construct_message_text(context)
    send_telegram_message(telegram_bot_token, telegram_chatid, text)

main()

Bên trên là bản Scrip mẫu. Các bạn hãy thay token của mình vào đó. Ví dụ tôi thay vào sẽ thành.

#!/usr/bin/env python
# Telegram V2

# Copyright Mathias Kettner  2013  mk@mathias-kettner.de
#           Stefan Gehn      2016  stefan+cmk@srcxbox.net

# check_mk is free software;  you can redistribute it and/or modify it
# under the  terms of the  GNU General Public License  as published by
# the Free Software Foundation in version 2.  check_mk is  distributed
# in the hope that it will be useful, but WITHOUT ANY WARRANTY;  with-
# out even the implied warranty of  MERCHANTABILITY  or  FITNESS FOR A
# PARTICULAR PURPOSE. See the  GNU General Public License for more de-
# ails.  You should have  received  a copy of the  GNU  General Public
# License along with GNU Make; see the file  COPYING.  If  not,  write
# to the Free Software Foundation, Inc., 51 Franklin St,  Fifth Floor,
# Boston, MA 02110-1301 USA.

# Telegram notification based on asciimail notification from
# check_mk 1.2.6p16.

import os
import re
import sys
reload(sys)
sys.setdefaultencoding('utf8')
import urllib
import urllib2
### CHANGE THESE ###
telegram_bot_token = '908652940:AAGYGskRFhRr42cy4or1FynDMtfKKzTIs6w'
####################

tmpl_host_text = """*Check_MK: $HOSTNAME$ - $EVENT_TXT$*
```
Host:     $HOSTNAME$
Alias:    $HOSTALIAS$
Address:  $HOSTADDRESS$
Event:    $EVENT_TXT$
Output:   $HOSTOUTPUT$

$LONGHOSTOUTPUT$```"""

tmpl_service_text = """*Check_MK: $HOSTNAME$/$SERVICEDESC$ $EVENT_TXT$*
```
Host:     $HOSTNAME$
Alias:    $HOSTALIAS$
Address:  $HOSTADDRESS$
Service:  $SERVICEDESC$
Event:    $EVENT_TXT$
Output:   $SERVICEOUTPUT$

$LONGSERVICEOUTPUT$```"""

def substitute_context(template, context):
    # First replace all known variables
    for varname, value in context.items():
        template = template.replace('$'+varname+'$', value)

    # Remove the rest of the variables and make them empty
    template = re.sub("\$[A-Z_][A-Z_0-9]*\$", "", template)
    return template

def construct_message_text(context):
    notification_type = context["NOTIFICATIONTYPE"]
    if notification_type in [ "PROBLEM", "RECOVERY" ]:
        txt_info = "$PREVIOUS@HARDSHORTSTATE$ -> $@SHORTSTATE$"
    elif notification_type.startswith("FLAP"):
        if "START" in notification_type:
            txt_info = "Started Flapping"
        else:
            txt_info = "Stopped Flapping ($@SHORTSTATE$)"
    elif notification_type.startswith("DOWNTIME"):
        what = notification_type[8:].title()
        txt_info = "Downtime " + what + " ($@SHORTSTATE$)"
    elif notification_type == "ACKNOWLEDGEMENT":
        txt_info = "Acknowledged ($@SHORTSTATE$)"
    elif notification_type == "CUSTOM":
        txt_info = "Custom Notification ($@SHORTSTATE$)"
    else:
        txt_info = notification_type # Should neven happen

    txt_info = substitute_context(txt_info.replace("@", context["WHAT"]), context)

    context["EVENT_TXT"] = txt_info

    if context['WHAT'] == 'HOST':
        tmpl_text = tmpl_host_text
    else:
        tmpl_text = tmpl_service_text

    return substitute_context(tmpl_text, context)

def fetch_notification_context():
    context = {}
    for (var, value) in os.environ.items():
        if var.startswith("NOTIFY_"):
            context[var[7:]] = value.decode("utf-8")
    return context

def send_telegram_message(token, chat_id, text):
    url = 'https://api.telegram.org/bot%s/sendMessage' % (token)
    data = urllib.urlencode({'chat_id':chat_id, 'text':text, 'parse_mode':'Markdown'})
    #print("sending telegram message, url '%s', chat id '%s', text '%s'" % (url, chat_id, text))
    try:
        urllib2.urlopen(url, data).read()
    except urllib2.URLError, e:
        sys.stdout.write('Cannot send Telegram message: HTTP-Error %s %s\n' % (e.code, e))

def main():
    context = fetch_notification_context()
    telegram_chatid = context.get('CONTACT_TELEGRAM_CHAT_ID')
    if not telegram_chatid: # e.g. empty field in user database
        sys.stdout.write("Cannot send Telegram message: Empty destination chat id")
        sys.exit(2)
    text = construct_message_text(context)
    send_telegram_message(telegram_bot_token, telegram_chatid, text)

main()

Thay TOKEN bằng TOKEN chúng ta lấy được qua chat box @BotFather

2. Cấp quyền cho file telegram.py

chmod +x /omd/sites/monitoring/share/check_mk/notifications/telegram.py

3. Restart lại omd server :

omd restart

4.  Cấu hình trên WATO

Trên WATO các bạn thực hiện các bước bên dưới như mình nhé!

Đâu tiền ta sẽ tạo thêm  Attributes User. Sau đó save và cập nhật thay đổi

Chúng ta sẽ điền thông tin của bot này. Lưu ý tên của trường được add thêm này sẽ được sử dụng để lấy giá trị trong plugin nên để tên giống để có thể sử dụng được plugin bên trên

NOTE : Theo mặc định thì sẽ mỗi user sẽ không có trường ID của telegram. Mặc định nó chỉ có trường Email và Pager nên ta có thể tạo thêm trường tại New attribute

  • Show in WATO host table : Hiển thị trực tiếp trong bảng user hay là không
  • Editable by Users : Cho phép user thường chỉnh sửa trường đó hay không
  • Add to monitoring configuration : Giá trị này có được sử dụng trong cảnh báo hay là không
Sau đó ta sẽ tạo ra một user để có thể gửi thông tin cảnh báo
Ta cần lưu ý và nhập vào mục username và Telegram ID để có thể gửi thông báo tới tele qua ID

NOTE : Ta có thể cảnh báo vào một bot; một channel; hay là một group trong telegram. Ở trên tôi đã ghi ID của một bot. Vì thế nó sẽ cảnh báo về bot đã được tạo. Để có thể cảnh báo về Group thì ta thay thế ID đó bằng ID của group mà ta muốn.

Nếu muốn cảnh báo về group ta tạo thêm group mới trong telegram.
Sau đó ta add bot mà ta đã tạo vào trong group
Ta chat trong group đó.

Sau đó ta Sử dụng HTTP API token để lấy ID của group chat với cú pháp


https://api.telegram.org/bot$token/getUpdates
ví dụ:
https://api.telegram.org/bot908652940:AAGYGskRFhRr42cy4or1FynDMtfKKzTIs6w/getUpdates
Và ID có dấu trừ đằng trước chính là ID của group.
Sau đó ta thay giá trị ID của group vào đây. Vậy là có thể cảnh báo về group rồi nhé.
1: Có thể tắt hoặc không tắt chức năng đăng nhập vào site
2: xác định đây là một user thường

Sau đó ta tạo ra cảnh báo với telegram

Tạo ra các rules thông báo mới cho telegram
Chúng ta tạo rules hãy chọn đúng tên như bên trên đã điền vào nhé
Đến đây là xong hãy lưu lại cập nhật để chúng bắt đầu hoạt động

Cuối cùng chúng ta hãy kiểm tra xem bot đã hoạt động chưa bằng cách tắt máy mà chúng ta theo dõi với telegram

Vậy là mọi thứ đã hoạt động bình thường. Đây là một con bot đơn giản bạn nào học ngôn ngữ rồi thì có thể tạo riêng cho mình một con bot khác và chỉ cần làm theo các bước như trên thôi. Cảm ơn các bạn và chúc các bạn thành công!