1
0

configure_zabbix_alerts.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. import json
  2. #ident "@(#)$Format:LocalFoodAI:configure_zabbix_alerts.py:%an:%ae:%ad:%cn:%ce:%cd:%H:%D:%N$"
  3. import urllib.request
  4. import os
  5. ZABBIX_URL = os.environ.get('ZABBIX_URL', 'http://192.168.130.170:8081/api_jsonrpc.php')
  6. ZABBIX_USER = os.environ.get('ZABBIX_USER', 'Admin')
  7. ZABBIX_PASS = os.environ.get('ZABBIX_PASS', '')
  8. DISCORD_WEBHOOK = os.environ.get('DISCORD_WEBHOOK', '')
  9. EMAIL_USER = os.environ.get('EMAIL_USER', 'lanfr144@gmail.com')
  10. EMAIL_PASS = os.environ.get('EMAIL_PASS', '')
  11. def zabbix_request(method, params, auth=None):
  12. payload = {
  13. 'jsonrpc': '2.0',
  14. 'method': method,
  15. 'params': params,
  16. 'id': 1
  17. }
  18. if auth:
  19. payload['auth'] = auth
  20. req = urllib.request.Request(ZABBIX_URL, data=json.dumps(payload).encode('utf-8'), headers={'Content-Type': 'application/json-rpc'})
  21. with urllib.request.urlopen(req) as response:
  22. res = json.loads(response.read().decode('utf-8'))
  23. if 'error' in res:
  24. print(f"Error in {method}: {res['error']}")
  25. return None
  26. return res['result']
  27. def main():
  28. # 1. Login
  29. auth_token = zabbix_request('user.login', {'username': ZABBIX_USER, 'password': ZABBIX_PASS})
  30. if not auth_token:
  31. print("Login failed")
  32. return
  33. print("Zabbix Auth Token:", auth_token)
  34. # 2. Configure Email Media Type
  35. # Find existing Email media type (type 0 = Email)
  36. email_mt = zabbix_request('mediatype.get', {'filter': {'type': '0'}}, auth_token)
  37. email_params = {
  38. 'type': '0',
  39. 'name': 'Email',
  40. 'smtp_server': 'smtp.gmail.com',
  41. 'smtp_port': '587',
  42. 'smtp_helo': 'gmail.com',
  43. 'smtp_email': EMAIL_USER,
  44. 'smtp_security': '1', # STARTTLS
  45. 'smtp_verify_peer': '0',
  46. 'smtp_verify_host': '0',
  47. 'smtp_authentication': '1',
  48. 'username': EMAIL_USER,
  49. 'passwd': EMAIL_PASS,
  50. 'content_type': '1' # HTML
  51. }
  52. if email_mt:
  53. email_params['mediatypeid'] = email_mt[0]['mediatypeid']
  54. zabbix_request('mediatype.update', email_params, auth_token)
  55. print("Updated Email Media Type")
  56. email_id = email_mt[0]['mediatypeid']
  57. else:
  58. res = zabbix_request('mediatype.create', email_params, auth_token)
  59. email_id = res['mediatypeids'][0]
  60. print("Created Email Media Type")
  61. # 3. Configure Discord Media Type (type 4 = Webhook)
  62. discord_script = """
  63. var req = new HttpRequest();
  64. req.addHeader('Content-Type: application/json');
  65. var webhook = params.URL;
  66. var payload = JSON.stringify({
  67. "content": params.Subject + "\\n" + params.Message
  68. });
  69. var resp = req.post(webhook, payload);
  70. if (req.getStatus() != 204 && req.getStatus() != 200) {
  71. throw 'Failed with status ' + req.getStatus();
  72. }
  73. return 'OK';
  74. """
  75. discord_mt = zabbix_request('mediatype.get', {'filter': {'name': 'Discord Webhook'}}, auth_token)
  76. discord_params = {
  77. 'name': 'Discord Webhook',
  78. 'type': '4',
  79. 'parameters': [
  80. {'name': 'URL', 'value': DISCORD_WEBHOOK},
  81. {'name': 'Subject', 'value': '{ALERT.SUBJECT}'},
  82. {'name': 'Message', 'value': '{ALERT.MESSAGE}'}
  83. ],
  84. 'script': discord_script,
  85. 'process_tags': '0'
  86. }
  87. if discord_mt:
  88. discord_params['mediatypeid'] = discord_mt[0]['mediatypeid']
  89. zabbix_request('mediatype.update', discord_params, auth_token)
  90. print("Updated Discord Media Type")
  91. discord_id = discord_mt[0]['mediatypeid']
  92. else:
  93. res = zabbix_request('mediatype.create', discord_params, auth_token)
  94. discord_id = res['mediatypeids'][0]
  95. print("Created Discord Media Type")
  96. # 4. Update Admin User Media
  97. users = zabbix_request('user.get', {'filter': {'username': 'Admin'}, 'selectMedias': 'extend'}, auth_token)
  98. if users:
  99. admin_id = users[0]['userid']
  100. medias = [
  101. {'mediatypeid': email_id, 'sendto': [EMAIL_USER], 'active': 0, 'severity': 63, 'period': '1-7,00:00-24:00'},
  102. {'mediatypeid': discord_id, 'sendto': ['Discord'], 'active': 0, 'severity': 63, 'period': '1-7,00:00-24:00'}
  103. ]
  104. zabbix_request('user.update', {'userid': admin_id, 'medias': medias}, auth_token)
  105. print("Updated Admin user media")
  106. # 5. Create Web Scenario & Trigger for "> 5 seconds"
  107. hosts = zabbix_request('host.get', {'filter': {'host': 'Zabbix server'}}, auth_token)
  108. if hosts:
  109. host_id = hosts[0]['hostid']
  110. # Create web scenario
  111. httptests = zabbix_request('httptest.get', {'filter': {'name': 'Food App Performance'}}, auth_token)
  112. if not httptests:
  113. zabbix_request('httptest.create', {
  114. 'name': 'Food App Performance',
  115. 'hostid': host_id,
  116. 'delay': '30s',
  117. 'steps': [
  118. {
  119. 'name': 'Homepage',
  120. 'url': 'http://172.18.0.3:8501', # Using docker internal IP or host IP
  121. 'status_codes': '200',
  122. 'no': 1
  123. }
  124. ]
  125. }, auth_token)
  126. print("Created HTTP Test for Food App")
  127. # Create Trigger > 5s
  128. triggers = zabbix_request('trigger.get', {'filter': {'description': 'Food App is too slow (> 5s)'}}, auth_token)
  129. if not triggers:
  130. zabbix_request('trigger.create', {
  131. 'description': 'Food App is too slow (> 5s)',
  132. 'expression': f'last(/Zabbix server/web.test.time[Food App Performance,Homepage,resp])>5',
  133. 'priority': 4 # High
  134. }, auth_token)
  135. print("Created Trigger for slow performance")
  136. triggers_down = zabbix_request('trigger.get', {'filter': {'description': 'Food App is DOWN'}}, auth_token)
  137. if not triggers_down:
  138. zabbix_request('trigger.create', {
  139. 'description': 'Food App is DOWN',
  140. 'expression': f'last(/Zabbix server/web.test.fail[Food App Performance])<>0',
  141. 'priority': 5 # Disaster
  142. }, auth_token)
  143. print("Created Trigger for downtime")
  144. # 6. Action to send message
  145. actions = zabbix_request('action.get', {'filter': {'name': 'Alert Discord and Email'}}, auth_token)
  146. if not actions:
  147. zabbix_request('action.create', {
  148. 'name': 'Alert Discord and Email',
  149. 'eventsource': 0,
  150. 'status': 0,
  151. 'esc_period': '1m',
  152. 'filter': {
  153. 'evaltype': 0,
  154. 'conditions': [
  155. {'conditiontype': 3, 'operator': 2, 'value': 'Food App'} # Trigger name contains "Food App"
  156. ]
  157. },
  158. 'operations': [
  159. {
  160. 'operationtype': 0,
  161. 'opmessage': {
  162. 'default_msg': 1,
  163. 'mediatypeid': 0 # all
  164. },
  165. 'opmessage_usr': [
  166. {'userid': admin_id}
  167. ]
  168. }
  169. ]
  170. }, auth_token)
  171. print("Created Action for Alerts")
  172. print("Zabbix Configuration Complete.")
  173. if __name__ == '__main__':
  174. main()