Hướng dẫn cảnh báo checkmk cùng với telegram

30/12/2020

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

Đâ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.

4. Chat với bot

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

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  [email protected] #           Stefan Gehn      2016  [email protected]  # 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 %sn' % (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  [email protected] #           Stefan Gehn      2016  [email protected]  # 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 %sn' % (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

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

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.

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

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

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!

ONET IDC thành lập vào năm 2012, là công ty chuyên nghiệp tại Việt Nam trong lĩnh vực cung cấp dịch vụ Hosting, VPS, máy chủ vật lý, dịch vụ Firewall Anti DDoS, SSL… Với 10 năm xây dựng và phát triển, ứng dụng nhiều công nghệ hiện đại, ONET IDC đã giúp hàng ngàn khách hàng tin tưởng lựa chọn, mang lại sự ổn định tuyệt đối cho website của khách hàng để thúc đẩy việc kinh doanh đạt được hiệu quả và thành công.
Bài viết liên quan

[BigBlueButton][HDSD-1]-Hướng dẫn tạo phòng meeting trên BigBlueButton

Onet đã hướng dẫn cách cài đặt và đăng nhập vào BigBlueButton(BBB) trong bài viết trước. Trong...
30/12/2020

Nextcloud [Part 5] – Cài đặt NextCloud client trên PC và mobile

Mục lục Cài đặt NextCloud client trên PC Windows Cài đặt NextCloud client trên PC Linux Cài đặt NextCloud...
30/12/2020

[Cobbler] Cài đặt cobbler server trên CentOS7

Thật đơn giản để bạn có thể triển khai một PXE server trên môi trường Linux mà không cần...
30/12/2020
Bài Viết

Bài Viết Mới Cập Nhật

Mua proxy v4 chạy socks5 để chơi game an toàn, tốc độ cao ở đâu?
18/05/2024

Thuê mua proxy Telegram trọn gói, tốc độ cao, giá siêu hời
18/05/2024

Thuê mua proxy Viettel ở đâu uy tín, chất lượng và giá tốt? 
14/05/2024

Dịch vụ thuê mua proxy US UK uy tín, chất lượng số #1
13/05/2024

Thuê mua proxy Việt Nam: Báo giá & các thông tin MỚI NHẤT
13/05/2024