configure_zabbix_teams.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. import requests
  2. import json
  3. import os
  4. ZABBIX_API_URL = "http://zabbix-web:8080/api_jsonrpc.php"
  5. ZABBIX_USER = "Admin"
  6. ZABBIX_PASSWORD = "zabbix"
  7. TEAMS_WEBHOOK_URL = "https://webhookbot.c-toss.com/api/bot/webhooks/7accc381-ae55-423c-9c08-6764c2813c8a"
  8. def authenticate():
  9. payload = {"jsonrpc": "2.0", "method": "user.login", "params": {"username": ZABBIX_USER, "password": ZABBIX_PASSWORD}, "id": 1}
  10. try:
  11. response = requests.post(ZABBIX_API_URL, json=payload).json()
  12. return response.get('result')
  13. except Exception as e:
  14. print(f"Error connecting to Zabbix API: {e}")
  15. return None
  16. def configure_teams(auth_token):
  17. print("Checking if MS Teams Webhook Media Type already exists...")
  18. check_payload = {
  19. "jsonrpc": "2.0",
  20. "method": "mediatype.get",
  21. "params": {
  22. "output": ["mediatypeid", "name"],
  23. "search": {"name": "MS Teams Custom Webhook"}
  24. },
  25. "id": 2,
  26. "auth": auth_token
  27. }
  28. existing = requests.post(ZABBIX_API_URL, json=check_payload).json().get('result', [])
  29. if existing:
  30. media_type_id = existing[0]['mediatypeid']
  31. print(f"Media Type already exists with ID {media_type_id}. Updating it...")
  32. update_payload = {
  33. "jsonrpc": "2.0",
  34. "method": "mediatype.update",
  35. "params": {
  36. "mediatypeid": media_type_id,
  37. "parameters": [
  38. { "name": "URL", "value": TEAMS_WEBHOOK_URL },
  39. { "name": "Message", "value": "{ALERT.SUBJECT}\\n{ALERT.MESSAGE}" }
  40. ]
  41. },
  42. "id": 3,
  43. "auth": auth_token
  44. }
  45. requests.post(ZABBIX_API_URL, json=update_payload)
  46. else:
  47. print("Creating MS Teams Webhook Media Type...")
  48. create_payload = {
  49. "jsonrpc": "2.0",
  50. "method": "mediatype.create",
  51. "params": {
  52. "type": 4, # 4 = Webhook
  53. "name": "MS Teams Custom Webhook",
  54. "script": "var req = new HttpRequest(); req.addHeader('Content-Type: application/json'); var params = JSON.parse(value); var payload = {'text': params.Message}; var resp = req.post(params.URL, JSON.stringify(payload)); Zabbix.log(4, '[Teams Webhook] response: ' + resp); return 'OK';",
  55. "parameters": [
  56. { "name": "URL", "value": TEAMS_WEBHOOK_URL },
  57. { "name": "Message", "value": "{ALERT.SUBJECT}\\n{ALERT.MESSAGE}" }
  58. ]
  59. },
  60. "id": 4,
  61. "auth": auth_token
  62. }
  63. res = requests.post(ZABBIX_API_URL, json=create_payload).json()
  64. if 'result' in res:
  65. media_type_id = res['result']['mediatypeids'][0]
  66. print(f"Created Media Type with ID: {media_type_id}")
  67. else:
  68. print(f"Failed to create Media Type: {res}")
  69. return
  70. # Assign to Admin user
  71. print("Assigning Teams Webhook to Admin User...")
  72. user_payload = {
  73. "jsonrpc": "2.0",
  74. "method": "user.update",
  75. "params": {
  76. "userid": "1",
  77. "medias": [
  78. {
  79. "mediatypeid": "1", # Email
  80. "sendto": ["lanfr144@gmail.com"],
  81. "active": 0,
  82. "severity": 63,
  83. "period": "1-7,00:00-24:00"
  84. },
  85. {
  86. "mediatypeid": media_type_id, # Teams
  87. "sendto": ["teams"],
  88. "active": 0,
  89. "severity": 63,
  90. "period": "1-7,00:00-24:00"
  91. }
  92. ]
  93. },
  94. "id": 5,
  95. "auth": auth_token
  96. }
  97. res = requests.post(ZABBIX_API_URL, json=user_payload).json()
  98. if 'result' in res:
  99. print("User media successfully updated to include Teams.")
  100. else:
  101. print(f"Failed to update user media: {res}")
  102. # Ensure action is enabled
  103. print("Enabling Report problems to Zabbix administrators action...")
  104. action_search = {
  105. "jsonrpc": "2.0",
  106. "method": "action.get",
  107. "params": {
  108. "output": ["actionid", "name"],
  109. "search": {"name": "Report problems to Zabbix administrators"}
  110. },
  111. "id": 6,
  112. "auth": auth_token
  113. }
  114. actions = requests.post(ZABBIX_API_URL, json=action_search).json().get('result', [])
  115. if actions:
  116. action_id = actions[0]['actionid']
  117. action_enable = {
  118. "jsonrpc": "2.0",
  119. "method": "action.update",
  120. "params": {"actionid": action_id, "status": 0},
  121. "id": 7,
  122. "auth": auth_token
  123. }
  124. requests.post(ZABBIX_API_URL, json=action_enable)
  125. print("Action verified and enabled.")
  126. # Send a test message
  127. test_payload = {
  128. "text": "Hello World, From Zabbix Automated Webhook Script!"
  129. }
  130. print("Sending test message to Teams...")
  131. try:
  132. requests.post(TEAMS_WEBHOOK_URL, json=test_payload)
  133. print("Test message sent!")
  134. except Exception as e:
  135. print(f"Failed to send test message: {e}")
  136. if __name__ == "__main__":
  137. token = authenticate()
  138. if token:
  139. configure_teams(token)
  140. else:
  141. print("Failed to authenticate to Zabbix API.")