|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# |
| 3 | +# Referência |
| 4 | +# https://www.youtube.com/watch?v=Ko8CJUqSqws |
| 5 | +# https://wiki.tiozaodolinux.com/Guide-for-Linux/Zabbix-Telegram-With-Graphic |
| 6 | +# |
| 7 | + |
| 8 | +import os |
| 9 | +import sys |
| 10 | +import subprocess |
| 11 | + |
| 12 | +# Função para verificar e instalar dependências |
| 13 | +def check_dependencies(): |
| 14 | + try: |
| 15 | + import requests |
| 16 | + except ImportError: |
| 17 | + print("A biblioteca 'requests' não está instalada. Instalando agora...") |
| 18 | + subprocess.check_call([sys.executable, "-m", "pip", "install", "requests"]) |
| 19 | + import requests |
| 20 | + |
| 21 | +# Verifica dependências antes de continuar |
| 22 | +check_dependencies() |
| 23 | + |
| 24 | +import requests |
| 25 | +import base64 |
| 26 | + |
| 27 | +# Função para forçar o usuário a passar os parâmetros necessários |
| 28 | +def check_arguments(): |
| 29 | + expected_args = 10 |
| 30 | + if len(sys.argv) != expected_args: |
| 31 | + print(f"Erro: Número incorreto de argumentos fornecidos.") |
| 32 | + print(f"Usage: {sys.argv[0]} {{URLZBX}} {{USERZBX}} {{PWDZBX}} {{ITEMIDZBX}} {{URLAPI}} {{TOKEN}} {{TO}} {{SUBJECT}} {{MSG}}\n") |
| 33 | + print(f"Example:\n{'='*8}") |
| 34 | + print(f"{sys.argv[0]} https://zabbix.seudominio.com Admin zabbix 48061 https://api.seudominio.com KHKHKHGKGJ 550000000000 'Subject' 'Msg from to WhatsApp'") |
| 35 | + print(f"\n") |
| 36 | + sys.exit(1) |
| 37 | + |
| 38 | + url_zbx = sys.argv[1] |
| 39 | + user_zbx = sys.argv[2] |
| 40 | + pwd_zbx = sys.argv[3] |
| 41 | + item_id_zbx = sys.argv[4] |
| 42 | + url_api = sys.argv[5] |
| 43 | + token = sys.argv[6] |
| 44 | + to = sys.argv[7] |
| 45 | + subject = sys.argv[8] |
| 46 | + msg = sys.argv[9] |
| 47 | + |
| 48 | + if not url_zbx.startswith("http://") and not url_zbx.startswith("https://"): |
| 49 | + print("Erro: URLZBX deve começar com 'http://' ou 'https://'.") |
| 50 | + sys.exit(1) |
| 51 | + if not user_zbx: |
| 52 | + print("Erro: USERZBX não pode estar vazio.") |
| 53 | + sys.exit(1) |
| 54 | + if not pwd_zbx: |
| 55 | + print("Erro: PWDZBX não pode estar vazio.") |
| 56 | + sys.exit(1) |
| 57 | + if not item_id_zbx.isdigit(): |
| 58 | + print("Erro: ITEMIDZBX deve ser um número.") |
| 59 | + sys.exit(1) |
| 60 | + if not url_api.startswith("http://") and not url_api.startswith("https://"): |
| 61 | + print("Erro: URLAPI deve começar com 'http://' ou 'https://'.") |
| 62 | + sys.exit(1) |
| 63 | + if not token: |
| 64 | + print("Erro: TOKEN não pode estar vazio.") |
| 65 | + sys.exit(1) |
| 66 | + if not to.isdigit(): |
| 67 | + print("Erro: TO deve ser um número.") |
| 68 | + sys.exit(1) |
| 69 | + if not subject: |
| 70 | + print("Erro: SUBJECT não pode estar vazio.") |
| 71 | + sys.exit(1) |
| 72 | + if not msg: |
| 73 | + print("Erro: MSG não pode estar vazio.") |
| 74 | + sys.exit(1) |
| 75 | + |
| 76 | +# Função principal |
| 77 | +def main(): |
| 78 | + check_arguments() |
| 79 | + |
| 80 | + # Parâmetros extras para o gráfico |
| 81 | + _from = "now-6h" # Tempo inicial |
| 82 | + _to = "now" # Tempo final |
| 83 | + _with = "1024" # Largura do gráfico |
| 84 | + _height = "220" # Altura do gráfico |
| 85 | + _type = "0" # 0=linha simples, 1=empilhado quando há mais de um parâmetro no mesmo gráfico |
| 86 | + _profileIdx = "web.item.graph.filter" # Função do gráfico |
| 87 | + |
| 88 | + # Leitura dos parâmetros obrigatórios |
| 89 | + _ZABBIX_BASE = sys.argv[1] # URLZBX: URL base do Zabbix |
| 90 | + _ZABBIX_USER = sys.argv[2] # USERXBX: usuário com permissão de leitura |
| 91 | + _ZABBIX_PASSWORD = sys.argv[3] # PWDZBX: senha do usuário |
| 92 | + _ZABBIX_ITEM_ID = sys.argv[4] # ITEMID: Ex: 48061 - Utilização de CPU do Zabbix Server (%) |
| 93 | + _WA_API_URL = sys.argv[5] # URLAPI: API do WhatsApp para enviar imagens |
| 94 | + _WA_TOKEN = sys.argv[6] # Token da API |
| 95 | + _WA_TO = sys.argv[7] # Destinatário do WhatsApp |
| 96 | + _WA_SUBJECT = sys.argv[8] # Assunto |
| 97 | + _WA_MSG = sys.argv[9] # Mensagem a ser enviada no WhatsApp |
| 98 | + |
| 99 | + # Sessão do requests |
| 100 | + session = requests.Session() |
| 101 | + |
| 102 | + # URL do login |
| 103 | + login_url = f'{_ZABBIX_BASE}/index.php' |
| 104 | + |
| 105 | + # Dados do formulário de login |
| 106 | + login_data = { |
| 107 | + 'name': _ZABBIX_USER, |
| 108 | + 'password': _ZABBIX_PASSWORD, |
| 109 | + 'enter': 'Sign in', |
| 110 | + 'autologin': 1, |
| 111 | + 'request': login_url |
| 112 | + } |
| 113 | + |
| 114 | + # Faz login |
| 115 | + response = session.post(login_url, data=login_data) |
| 116 | + |
| 117 | + # Verifica se o login foi bem-sucedido |
| 118 | + if 'Falha no login' in response.text: |
| 119 | + print('Falha no login') |
| 120 | + sys.exit(1) |
| 121 | + |
| 122 | + # URL do gráfico específico |
| 123 | + graph_url = f'{_ZABBIX_BASE}/chart.php?from={_from}&to={_to}&itemids[0]={_ZABBIX_ITEM_ID}&type={_type}&profileIdx={_profileIdx}&width={_with}&height={_height}' |
| 124 | + |
| 125 | + # Faz a requisição do gráfico |
| 126 | + graph_response = session.get(graph_url) |
| 127 | + |
| 128 | + # Verifica se a requisição foi bem-sucedida |
| 129 | + if graph_response.status_code != 200: |
| 130 | + print('Falha ao obter o gráfico') |
| 131 | + sys.exit(1) |
| 132 | + |
| 133 | + # Codifica a imagem em base64 diretamente da resposta |
| 134 | + base64_image = base64.b64encode(graph_response.content).decode('utf-8') |
| 135 | + |
| 136 | + # Prepara a mensagem para enviar via WhatsApp API |
| 137 | + wa_msg = f"{_WA_SUBJECT}\n{_WA_MSG}" |
| 138 | + |
| 139 | + # Envia a imagem via WhatsApp API |
| 140 | + wa_send_url = f'{_WA_API_URL}/sistema/sendImageBase64Grupo' |
| 141 | + data = { |
| 142 | + 'SessionName': _WA_TOKEN, |
| 143 | + 'groupId': _WA_TO, |
| 144 | + 'base64': base64_image, |
| 145 | + 'originalname': f'graph_zabbix_{_ZABBIX_ITEM_ID}.png', |
| 146 | + 'caption': wa_msg |
| 147 | + } |
| 148 | + headers = {'Content-Type': 'application/json'} |
| 149 | + |
| 150 | + response = requests.post(wa_send_url, json=data, headers=headers) |
| 151 | + |
| 152 | + # Verifica se o envio foi bem-sucedido |
| 153 | + if response.status_code == 200: |
| 154 | + print('Mensagem e gráfico enviados com sucesso') |
| 155 | + else: |
| 156 | + print('Falha ao enviar mensagem e gráfico') |
| 157 | + |
| 158 | +# Executa a função principal |
| 159 | +if __name__ == "__main__": |
| 160 | + main() |
0 commit comments