templates-zabbix-itguys/export_templates.py

130 lines
4.6 KiB
Python
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import requests
import json
import sys
from datetime import datetime
# ==============================================================================
# 🛠️ CONFIGURAÇÕES (JÁ PREENCHIDAS COM BASE NO ANTERIOR)
# ==============================================================================
ZABBIX_URL = "http://172.16.254.11/zabbix/api_jsonrpc.php"
ZABBIX_USER = "Admin"
ZABBIX_PASS = "M@dC@tMK11"
OUTPUT_FILE = "zabbix_templates_export.json"
def zabbix_api_call(method, params, auth_token=None, request_id=1):
headers = {'Content-Type': 'application/json-rpc'}
payload = {
"jsonrpc": "2.0",
"method": method,
"params": params,
"id": request_id
}
if auth_token:
# Lógica inteligente de Auth (Header vs Body)
if str(auth_token).startswith("USE_HEADER:"):
real_token = auth_token.split(":", 1)[1]
headers["Authorization"] = f"Bearer {real_token}"
else:
payload["auth"] = auth_token
try:
response = requests.post(ZABBIX_URL, data=json.dumps(payload), headers=headers, verify=False, timeout=60)
response.raise_for_status()
decoded = response.json()
if 'error' in decoded:
print(f"❌ Erro API ({method}): {decoded['error'].get('data')}")
sys.exit(1)
return decoded['result']
except Exception as e:
print(f"❌ Erro Conexão: {e}")
sys.exit(1)
def main():
requests.packages.urllib3.disable_warnings()
print("="*60)
print(" 📦 EXPORTADOR DE TEMPLATES ZABBIX")
print("="*60)
# 1. Auth e Versão
print("🔐 1. Autenticando...", end=" ")
api_info = zabbix_api_call("apiinfo.version", {}, None)
# Tenta Auth Moderna (Username)
try:
auth_token = zabbix_api_call("user.login", {"username": ZABBIX_USER, "password": ZABBIX_PASS})
except SystemExit:
auth_token = zabbix_api_call("user.login", {"user": ZABBIX_USER, "password": ZABBIX_PASS})
# Adapta para Header se for Zabbix novo
try:
if float(api_info[:3]) >= 6.4:
auth_token = f"USE_HEADER:{auth_token}"
except: pass
print(f"✅ OK (API {api_info})")
# 2. Listar Templates
print("\n📋 2. Buscando TODOS os templates...", end=" ")
templates = zabbix_api_call("template.get", {
"output": ["templateid", "name"],
"preservekeys": True
}, auth_token)
tpl_ids = list(templates.keys())
count = len(tpl_ids)
print(f"{count} templates encontrados.")
if count == 0: return
# 3. Exportar (EM LOTES para evitar Error 500)
print(f"\n📦 3. Baixando templates em lotes (evita timeout)...")
BATCH_SIZE = 50
all_export_data = {"zabbix_export": {"version": "6.0", "templates": []}} # Estrutura base
# Nota: A fusão de JSONs de exportação é complexa.
# Para simplificar e garantir que tenhamos os dados, vamos salvar VÁRIOS arquivos se der erro 500 no massivo,
# OU tentar exportar um por um se o lote falhar.
# Mas o configuration.export não suporta append fácil.
# TENTATIVA 1: Exportar tudo (já falhou com 500).
# TENTATIVA 2: Exportar 1 a 1 e salvar numa pasta 'templates_bkp'?
# Ou exportar em 2 ou 3 grandes blocos. Vamos tentar blocos menores.
import os
if not os.path.exists("templates_export"):
os.makedirs("templates_export")
total_exported = 0
for i in range(0, count, BATCH_SIZE):
batch_ids = tpl_ids[i : i + BATCH_SIZE]
print(f" ⏳ Processando lote {i+1} a {min(i+BATCH_SIZE, count)}...", end=" ")
try:
batch_data = zabbix_api_call("configuration.export", {
"options": {"templates": batch_ids},
"format": "json"
}, auth_token)
# Salva lote individualmente para garantir
filename = f"templates_export/batch_{i//BATCH_SIZE + 1}.json"
with open(filename, 'w', encoding='utf-8') as f:
if isinstance(batch_data, str): f.write(batch_data)
else: json.dump(batch_data, f, indent=4, ensure_ascii=False)
print(f"✅ Salvo em {filename}")
total_exported += len(batch_ids)
except Exception as e:
print(f"❌ Falha no lote: {e}")
print(f"\n✅ Total exportado: {total_exported}/{count} templates.")
print(f"📂 Os arquivos estão na pasta 'templates_export/'")
print(" Devido ao erro 500, dividimos em vários arquivos para garantir que você tenha tudo.")
if __name__ == "__main__":
main()