forked from janssenlima/ZabbixTuner
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ZabbixTuner.py
executable file
·486 lines (432 loc) · 19.8 KB
/
ZabbixTuner.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
#!/usr/bin/python
#coding: utf-8
__author__ = "Janssen dos Reis Lima"
from zabbix_api import ZabbixAPI
import os, sys
#from os import *
import datetime
import time
import csv
from termcolor import colored
from progressbar import ProgressBar, Percentage, ReverseBar, ETA, Timer, RotatingMarker
from conf.zabbix import *
def banner():
print colored('''
______ ______ ______ _____ ________
___ /______ ___ /____ /____(_)___ __ ___ __/___ _____________________
__ / _ __ `/_ __ \_ __ \_ /__ |/_/ __ / _ / / /_ __ \ _ \_ ___/
_ /__/ /_/ /_ /_/ / /_/ / / __> < _ / / /_/ /_ / / / __/ /
/____/\__,_/ /_.___//_.___//_/ /_/|_| /_/ \__,_/ /_/ /_/\___//_/
''', 'red', attrs=['bold'])
print ""
try:
zapi = ZabbixAPI(server=server, path="", timeout=timeout ,log_level=loglevel)
zapi.login(username, password)
except:
os.system('clear')
banner()
print colored(' Não foi possível conectar ao Zabbix Server.', 'yellow', attrs=['bold'])
print u"\n Verifique se a URL " + colored (server, 'red', attrs=['bold']) + u" está disponível."
print ""
print colored('''
Desenvolvido por Janssen Lima - [email protected]
''', 'blue', attrs=['bold'])
exit(0)
def menu():
os.system('clear')
banner()
print colored("[+] - Bem-vindo ao ZABBIX TUNER - [+]\n"
"[+] - Zabbix Tuner faz um diagnóstico do seu ambiente e propõe melhorias na busca de um melhor desempenho - [+]\n"
"[+] - Desenvolvido por Janssen Lima - [+]\n"
"[+] - Dúvidas/Sugestões envie e-mail para [email protected] - [+]", 'blue')
print ""
print colored("--- Escolha uma opção do menu ---",'yellow', attrs=['bold'])
print ""
print "[1] - Relatório de itens do sistema"
print "[2] - Listar itens não suportados"
print "[3] - Desabilitar itens não suportados"
print "[4] - Relatório da média de coleta dos itens (por tipo)"
print "[5] - Iniciar diagnóstico"
print "[6] - Relatório de Agentes Zabbix desatualizados"
print "[7] - Relatório de Triggers por tempo de alarme e estado"
print ""
print "[0] - Sair"
print ""
menu_opcao()
def menu_opcao():
opcao = raw_input( "[+] - Selecione uma opção[0-7]: ")
if opcao == '1':
dadosItens()
elif opcao == '2':
listagemItensNaoSuportados()
elif opcao == '3':
desabilitaItensNaoSuportados()
elif opcao == '5':
diagnosticoAmbiente()
elif opcao == '6':
agentesDesatualizados()
elif opcao == '7':
menu_relack()
elif opcao == '0':
sys.exit()
else:
menu()
def desabilitaItensNaoSuportados():
query = {
"output": "extend",
"filter": {
"state": 1
},
"monitored": True
}
filtro = raw_input('Qual a busca para key_? [NULL = ENTER] ')
if filtro.__len__() > 0:
query['search']={'key_': filtro}
limite = raw_input('Qual o limite de itens? [NULL = ENTER] ')
if limite.__len__() > 0:
try:
query['limit']=int(limite)
except:
print 'Limite invalido'
raw_input("Pressione ENTER para voltar")
main()
opcao = raw_input("Confirma operação? [s/n]")
if opcao == 's' or opcao == 'S':
itens = zapi.item.get(query)
print 'Encontramos {} itens'.format(itens.__len__())
bar = ProgressBar(maxval=itens.__len__(),widgets=[Percentage(), ReverseBar(), ETA(), RotatingMarker(), Timer()]).start()
i = 0
for x in itens:
result = zapi.item.update({"itemid": x['itemid'], "status": 1})
i += 1
bar.update(i)
bar.finish()
print "Itens desabilitados!!!"
raw_input("Pressione ENTER para continuar")
main()
def agentesDesatualizados():
itens = zapi.item.get ({
"filter": {"key_": "agent.version"},
"output": ["lastvalue", "hostid"],
"templated": False,
"selectHosts": ["host"],
"sortorder": "ASC"
})
try:
versaoZabbixServer = zapi.item.get ({
"filter": {"key_": "agent.version"},
"output": ["lastvalue", "hostid"],
"hostids": "10084"
})[0]["lastvalue"]
print colored('{0:6} | {1:30}' .format("Versão","Host"), attrs=['bold'])
for x in itens:
if x['lastvalue'] != versaoZabbixServer and x['lastvalue'] <= versaoZabbixServer:
print '{0:6} | {1:30}'.format(x["lastvalue"], x["hosts"][0]["host"])
print ""
raw_input("Pressione ENTER para continuar")
main()
except IndexError:
print "Não foi possível obter a versão do agent no Zabbix Server."
raw_input("Pressione ENTER para continuar")
main()
def diagnosticoAmbiente():
print colored("[+++]", 'green'), "analisando itens não númericos"
itensNaoNumericos = zapi.item.get ({
"output": "extend",
"monitored": True,
"filter": {"value_type": [1, 2, 4]},
"countOutput": True
})
print colored("[+++]", 'green'), "analisando itens ICMPPING com histórico acima de 7 dias"
itensPing = zapi.item.get ({
"output": "extend",
"monitored": True,
"filter": {"key_": "icmpping"},
})
contPing = 0
for x in itensPing:
if int(x["history"]) > 7:
contPing += 1
print ""
print colored("Resultado do diagnóstico:", attrs=['bold'])
print colored("[INFO]", 'blue'), "Quantidade de itens com chave icmpping armazenando histórico por mais de 7 dias:", contPing
print colored("[WARN]", 'yellow', None, attrs=['blink']), "Quantidade de itens não numéricos (ativos): ", itensNaoNumericos
print ""
raw_input("Pressione ENTER para continuar")
main()
def listagemItensNaoSuportados():
itensNaoSuportados = zapi.item.get({"output": ["itemid", "error", "name"],
"filter": {"state": 1,"status":0},
"monitored": True,
"selectHosts": ["hostid", "host"],
})
if itensNaoSuportados:
print colored('{0:5} | {1:30} | {2:40} | {3:10}' .format("Item","Nome", "Error", "Host"), attrs=['bold'])
for x in itensNaoSuportados:
print u'{0:5} | {1:30} | {2:40} | {3:10}'.format(x["itemid"], x["name"], x["error"], x["hosts"][0]["host"])
print ""
else:
print "Não há dados a exibir"
print ""
raw_input("Pressione ENTER para continuar")
main()
def dadosItens():
itensNaoSuportados = zapi.item.get({"output": "extend",
"filter": {"state": 1,"status": 0},
"monitored": True,
"countOutput": True
})
totalItensHabilitados = zapi.item.get({"output": "extend",
"filter": {"state": 0},
"monitored": True,
"countOutput": True
})
itensDesabilitados = zapi.item.get({"output": "extend",
"filter": {"status": 1, "flags": 0},
"templated": False,
"countOutput": True
})
"""
VERIFICAR PROBLEMA NESTA REQUISICAO
itensDescobertos = zapi.item.get({"output": "extend",
"selectItemDiscovery": ["itemid"],
"selectTriggers": ["description"],
"monitored": True
})
"""
itensZabbixAgent = zapi.item.get({"output": "extend",
"filter": {"type": 0},
"templated": False,
"countOutput": True,
"monitored": True
})
itensSNMPv1 = zapi.item.get({"output": "extend",
"filter": {"type": 1},
"templated": False,
"countOutput": True,
"monitored": True
})
itensZabbixTrapper = zapi.item.get({"output": "extend",
"filter": {"type": 2},
"templated": False,
"countOutput": True,
"monitored": True
})
itensChecagemSimples = zapi.item.get({"output": "extend",
"filter": {"type": 3},
"templated": False,
"countOutput": True,
"monitored": True
})
itensSNMPv2 = zapi.item.get({"output": "extend",
"filter": {"type": 4},
"templated": False,
"countOutput": True,
"monitored": True
})
itensZabbixInterno = zapi.item.get({"output": "extend",
"filter": {"type": 5},
"templated": False,
"countOutput": True,
"monitored": True
})
itensSNMPv3 = zapi.item.get({"output": "extend",
"filter": {"type": 6},
"templated": False,
"countOutput": True,
"monitored": True
})
itensZabbixAgentAtivo = zapi.item.get({"output": "extend",
"filter": {"type": 7},
"templated": False,
"countOutput": True,
"monitored": True
})
itensZabbixAggregate = zapi.item.get({"output": "extend",
"filter": {"type": 8},
"templated": False,
"countOutput": True,
"monitored": True
})
itensWeb = zapi.item.get({"output": "extend",
"filter": {"type": 9},
"templated": False,
"webitems": True,
"countOutput": True,
"monitored": True
})
itensExterno = zapi.item.get({"output": "extend",
"filter": {"type": 10},
"templated": False,
"countOutput": True,
"monitored": True
})
itensDatabase = zapi.item.get({"output": "extend",
"filter": {"type": 11},
"templated": False,
"countOutput": True,
"monitored": True
})
itensIPMI = zapi.item.get({"output": "extend",
"filter": {"type": 12},
"templated": False,
"countOutput": True,
"monitored": True
})
itensSSH = zapi.item.get({"output": "extend",
"filter": {"type": 13},
"templated": False,
"countOutput": True,
"monitored": True
})
itensTelnet = zapi.item.get({"output": "extend",
"filter": {"type": 14},
"templated": False,
"countOutput": True,
"monitored": True
})
itensCalculado = zapi.item.get({"output": "extend",
"filter": {"type": 15},
"templated": False,
"countOutput": True,
"monitored": True
})
itensJMX = zapi.item.get({"output": "extend",
"filter": {"type": 16},
"templated": False,
"countOutput": True,
"monitored": True
})
itensSNMPTrap = zapi.item.get({"output": "extend",
"filter": {"type": 17},
"templated": False,
"countOutput": True,
"monitored": True
})
"""
COMENTADO ATE RESOLVER O PROBLEMA NA REQUISICAO DOS ITENS DE DISCOVERY
cont = 0
for i in itensDescobertos:
if i["itemDiscovery"]:
cont += 1
"""
print ""
print "Relatório de itens"
print "=" * 18
print ""
print colored("[INFO]",'blue'), "Total de itens: ", int(totalItensHabilitados) + int(itensDesabilitados) + int(itensNaoSuportados)
print colored("[INFO]",'blue'), "Itens habilitados: ", totalItensHabilitados
print colored("[INFO]",'blue'), "Itens desabilitados: ", itensDesabilitados
if itensNaoSuportados > "0":
print colored("[ERRO]",'red'), "Itens não suportados: ", itensNaoSuportados
else:
print colored("[-OK-]",'green'), "Itens não suportados: ", itensNaoSuportados
#print colored("[INFO]",'blue'), "Itens descobertos: ", cont
print ""
print "Itens por tipo em monitoramento"
print "=" * 14
print colored("[INFO]",'blue'), "Itens Zabbix Agent (passivo): ", itensZabbixAgent
print colored("[INFO]",'blue'), "Itens Zabbix Agent (ativo): ", itensZabbixAgentAtivo
print colored("[INFO]",'blue'), "Itens Zabbix Trapper: ", itensZabbixTrapper
print colored("[INFO]",'blue'), "Itens Zabbix Interno: ", itensZabbixInterno
print colored("[INFO]",'blue'), "Itens Zabbix Agregado: ", itensZabbixAggregate
print colored("[INFO]",'blue'), "Itens SNMPv1: ", itensSNMPv1
print colored("[INFO]",'blue'), "Itens SNMPv2: ", itensSNMPv2
print colored("[INFO]",'blue'), "Itens SNMPv3: ", itensSNMPv3
print colored("[INFO]",'blue'), "Itens SNMNP Trap: ", itensSNMPTrap
print colored("[INFO]",'blue'), "Itens JMX: ", itensJMX
print colored("[INFO]",'blue'), "Itens IPMI: ", itensIPMI
print colored("[INFO]",'blue'), "Itens SSH: ", itensSSH
print colored("[INFO]",'blue'), "Itens Telnet: ", itensTelnet
print colored("[INFO]",'blue'), "Itens Web: ", itensWeb
print colored("[INFO]",'blue'), "Itens Checagem Simples: ", itensChecagemSimples
print colored("[INFO]",'blue'), "Itens Calculado: ", itensCalculado
print colored("[INFO]",'blue'), "Itens Checagem Externa: ", itensExterno
print colored("[INFO]",'blue'), "Itens Database: ", itensDatabase
print ""
raw_input("Pressione ENTER para continuar")
main()
def menu_relack():
os.system('clear')
banner()
print colored("[+] - Bem-vindo ao ZABBIX TUNER - [+]\n"
"[+] - Zabbix Tuner faz um diagnóstico do seu ambiente e propõe melhorias na busca de um melhor desempenho - [+]\n"
"[+] - Desenvolvido por Janssen Lima - [+]\n"
"[+] - Dúvidas/Sugestões envie e-mail para [email protected] - [+]", 'blue')
print ""
print colored("--- Escolha uma opção para o relatório ---",'yellow', attrs=['bold'])
print ""
print "[1] - Relatório de triggers com Acknowledged"
print "[2] - Relatório de triggers com Unacknowledged"
print "[3] - Relatório de triggers com ACK/UNACK"
print ""
print "[0] - Sair"
print ""
menu_opcao_relack()
def menu_opcao_relack():
opcao = raw_input( "[+] - Selecione uma opção[0-3]: ")
params = {'output': ['triggerid','lastchange','comments','description'],'selectHosts':['hostid', 'host'], 'expandDescription': True, 'only_true': True, 'active': True}
if opcao == '1':
params['withAcknowledgedEvents'] = True
label = 'ACK'
elif opcao == '2':
params['withUnacknowledgedEvents'] = True
label = 'UNACK'
elif opcao == '3':
label = 'ACK/UNACK'
elif opcao == '0':
main()
else:
raw_input("\nPressione ENTER para voltar")
menu_relack()
hoje = datetime.date.today()
try:
tmp_trigger = int(raw_input( "[+] - Selecione qual o tempo de alarme (dias): "))
except Exception, e:
raw_input("\nPressione ENTER para voltar")
menu_relack()
dt = (hoje - datetime.timedelta(days=tmp_trigger))
conversao = int(time.mktime(dt.timetuple()))
operador = raw_input( "[+] - Deseja ver Triggers com mais ou menos de {0} dias [ + / - ] ? ".format(tmp_trigger))
if operador == '+':
params['lastChangeTill'] = conversao
elif operador == '-':
params['lastChangeSince'] = conversao
else:
raw_input("\nPressione ENTER para voltar")
menu_relack()
rel_ack = zapi.trigger.get(params)
for relatorio in rel_ack:
lastchangeConverted = datetime.datetime.fromtimestamp(float(relatorio["lastchange"])).strftime('%Y-%m-%d %H:%M')
print ""
print colored("[-PROBLEM-]",'red'), "Trigger {} com {} de {} dias".format(label,operador,tmp_trigger)
print "=" * 80
print ""
print colored("[INFO]",'blue'), "Nome da Trigger: ", relatorio["description"],"| HOST:"+relatorio["hosts"][0]["host"]+" | ID:"+relatorio["hosts"][0]["hostid"]
print colored("[INFO]",'blue'), "Hora de alarme: ", lastchangeConverted
print colored("[INFO]",'blue'), "URL da trigger: {}/zabbix.php?action=problem.view&filter_set=1&filter_triggerids%5B%5D={}".format(server,relatorio["triggerid"])
print colored("[INFO]",'blue'), "Descrição da Trigger: ", relatorio["comments"]
print ""
print colored("\n[INFO]",'green'), "Total de {} triggers encontradas".format(rel_ack.__len__())
opcao = raw_input("\nDeseja gerar relatorio em arquivo? [s/n]")
if opcao == 's' or opcao == 'S':
with open("relatorio.csv" ,"w") as arquivo:
arquivo.write("Nome da Trigger,Hora de alarme:,URL da trigger:,Descrição da Trigger:\r\n ")
for relatorio in rel_ack:
arquivo.write((relatorio["description"]).encode('utf-8'))
arquivo.write(("| HOST:"+relatorio["hosts"][0]["host"]+" | ID:"+relatorio["hosts"][0]["hostid"]))
arquivo.write(",")
arquivo.write(lastchangeConverted)
arquivo.write(",")
arquivo.write("{}/zabbix.php?action=problem.view&filter_set=1&filter_triggerids%5B%5D={}".format(server,relatorio["triggerid"]))
arquivo.write(",")
arquivo.write(("\""+relatorio["comments"]+"\"").encode('utf-8'))
arquivo.write("\r\n")
raw_input("\nArquivo gerado com sucesso ! Pressione ENTER para voltar")
menu_relack()
else:
raw_input("\nPressione ENTER para voltar")
menu_relack()
def main():
menu()
main()