본문 바로가기

Monitoring Tools/Zabbix

zabbix | Slack Webhook을 이용하여 알람 보내기(그래프 포함)

반응형

zabbix server version 5.0

 

 

media types

  • Administrator - Media types - Create media type 아래와 같이 입력

 

 

  • Slack.py
    • 변수 :
      • zabbix_baseurl="zabbix web 주소"
      • chart_cookie="세션 쿠키 저장파일"
        • 설정할 파일경로 디렉토리를 생성 해주고 권한을 777로 설정
        • mkdir /usr/share/zabbix/tmp && chmod 777 /usr/share/zabbix/tmp
      • chart_basedir="그래프 저장할 path"
        • 설정할 파일경로 디렉토리를 생성 해주고 권한을 777로 설정
        • mkdir /usr/share/zabbix/slack_charts && chmod 777 /usr/share/zabbix/slack_charts
      • cmd_wget = "/usr/bin/wget"
        • wget은 설치 해야함.
        • yum install wget
      • zabbix_username="zabbix admin user"
      • zabbix_password="zabbix admin password"
#!/usr/bin/python3

import sys
import time
import datetime
import json
import os
import subprocess
from time import sleep

def trigger_color(trigger_status,trigger_severity):
	if trigger_status == 'OK':
		emoji = ':smile:'
		if trigger_severity == 'Information':
			color = "#439FE0"
		else:
			color = "good"
	elif trigger_status == 'PROBLEM':
		if trigger_severity == 'Information':
                        color = "#439FE0"
		elif trigger_severity == 'Warning':
			color = "warning"
		else:
			color = "danger"
	else:
		color = "danger"
	return(color)

def nowdate():
    now = datetime.datetime.now()
    now_f = now.strftime('%Y.%m.%d-%H:%M')
    return now_f

def graph_generate(item_id,now_f,host,zabbix_baseurl,chart_cookie,chart_basedir,cmd_wget,zabbix_username,zabbix_password):
	chart_url = 'graph-'+host+'-'+item_id+'-'+now_f+'.png'
	cmd = "{a} --save-cookies={b} -4 --keep-session-cookies -O - -S --post-data='name={c}&password={d}&enter=Enter' {e}/index.php?login=1".format(a=cmd_wget, b=chart_cookie, c=zabbix_username, d=zabbix_password, e=zabbix_baseurl)
	cmd2 = "{a} -4 --load-cookies={b} -O {c}/{d} '{e}/chart.php?from=now-1h&to=now&itemids%5B0%5D={f}&type=0&profileIdx=web.item.graph.filter&profileIdx2={f}&width=1082&height=200&_=v1smiflp'".format(a=cmd_wget, b=chart_cookie, c=chart_basedir, d=chart_url, e=zabbix_baseurl, f=item_id)
	try:
		subprocess.check_output(cmd, shell=True, universal_newlines=True)
		subprocess.check_output(cmd2, shell=True, universal_newlines=True)
		return(chart_url)
	except:
		return('Failed to create graph')

def append_payload(title,value,short,payload):
        append_data = {'title': title, 'value': value, 'short': short}
        payload['attachments'][0]['fields'].append(append_data)
        return(payload)

def delete_chart(chart_basedir,chart_url):
	cmd = "rm -rf {a}/{b}".format(a=chart_basedir,b=chart_url)
	sleep(1)
	subprocess.check_output(cmd, shell=True, universal_newlines=True)

slack_url = sys.argv[1]
slack_user = sys.argv[2]
channel = "#hq-zabbix"
title = sys.argv[3]
params = sys.argv[4]

#fp = open('b', 'r')
#params = fp.read()
param_j = json.loads(params)
emoji = ":slack:"
timeout = 10
cmd_curl = "/usr/bin/curl"

zabbix_baseurl="http://zabbix.test.com"
chart_cookie="/usr/share/zabbix/tmp/zcookies.txt"
chart_basedir="/usr/share/zabbix/slack_charts"
cmd_wget = "/usr/bin/wget"
zabbix_username="***"
zabbix_password="***"

trigger_url = zabbix_baseurl+'/history.php?action=showgraph&itemids%5B%5D='+param_j['ITEM_ID']
color = trigger_color(param_j['TRIGGER_STATUS'],param_j['TRIGGER_SEVERITY'])

now_f=nowdate()
chart_url = graph_generate(param_j['ITEM_ID'],now_f,param_j['HOST'],zabbix_baseurl,chart_cookie,chart_basedir,cmd_wget,zabbix_username,zabbix_password)

payload = {}
payload['channel'] = channel
payload['username'] = slack_user
payload['icon_emoji'] = emoji
payload['attachments'] = [{}]

payload['attachments'][0]['fallback'] = 'Date / Time: '+param_j['DATETIME']+' - '+title
payload['attachments'][0]['pretext'] = title
payload['attachments'][0]['title'] = title
payload['attachments'][0]['title_link'] = trigger_url
payload['attachments'][0]['color'] = color
payload['attachments'][0]['image_url'] = zabbix_baseurl + '/slack_charts/' + chart_url
payload['attachments'][0]['fields']=[{}]
payload['attachments'][0]['fields'][0]['title']='DATE / TIME'
payload['attachments'][0]['fields'][0]['value']=param_j['DATETIME']
payload['attachments'][0]['fields'][0]['short']='true'

payload=append_payload('Status',param_j['TRIGGER_STATUS'],'true',payload)
payload=append_payload('Host',param_j['HOST'],'true',payload)
payload=append_payload('Address',param_j['IP_ADDRESS'],'true',payload)
payload=append_payload('Trigger',param_j['TRIGGER_NAME']+': '+param_j['ITEM_VALUE'],'true',payload)
payload=append_payload('Severity',param_j['TRIGGER_SEVERITY'],'true',payload)
payload_json=json.dumps(payload)
#print(payload_json)
slack_send = "curl --tlsv1.2 -X POST --data-urlencode 'payload={a}' {b}".format(a=payload_json,b=slack_url)
subprocess.check_output(slack_send, shell=True, universal_newlines=True)
#delete_chart(chart_basedir,chart_url)

 

 

  • Slack message Test
    • message : {
      "TRIGGER_NAME": "Zabbix agent is not available (for 3m)",
      "TRIGGER_STATUS": "PROBLEM",
      "TRIGGER_SEVERITY": "Average",
      "TRIGGER_ID": "23042",
      "TRIGGER_URL": "",
      "EVENT_ID": "5790",
      "DATETIME": "2021.09.27 09:22:25",
      "HOST": "SV",
      "IP_ADDRESS": "",
      "ITEM_ID": "42565",
      "ITEM_NAME": "Zabbix agent availability",
      "ITEM_VALUE": "not available (0)"
      }

 

 

 

 

 

Actions

Configuration - Actions - Create action

  • Add 를 눌러 알람 받을 호스트 그룹 선택

 

 

  • Operations 
    • Send to users : user 선택
    • Send only to : media types 에서 만들었던  slack_webhook 선택
    • Subject : media types의 {ALERT.SUBJECT}와 대응
    • Message : media type의 {ALERT.MESSAGE} 와 대응

 

 

  • Recovery operations

 

  • Update operations

 

 

 

 

Users

Administration - Users - "Send to User에서 선택한 User 선택" - Media - Add

  • Type : slack_webhook 선택
  • Send to : slack 발신자는 임의로 입력할수 있음

 

  • Slack 수신 메세지

반응형