Skip to content

Instantly share code, notes, and snippets.

@contato318
Created August 29, 2017 12:44
Embed
What would you like to do?
#!/usr/bin/perl
use strict;
use warnings;
##########################
# Banco de dados local #
##########################
use DBI;
my $dbh = DBI->connect(
"dbi:SQLite:dbname=/zabbix/share/zabbix/alertscripts/bd_chamados.db",
"",
"",
{ RaiseError => 1 },
) or die $DBI::errstr;
my $erro=0;
my $mensagem=" ";
open FILE, ">>/var/tmp/conector.log" or die $!;
print FILE "\n\n-------------INICIO---------------\n";
print FILE scalar localtime(time());
my @linhas = split("\n", $ARGV[2]);
my $valor = " ";
my %zabbix = ();
print FILE "\n-----------";
#####################################
# OBTENDO OS DADOS VINDOS DO ZABBIX #
#####################################
foreach $valor (@linhas){
my @campos=split(":=",$valor);
if (! $campos[1]) {
print FILE "\n IMPOSSIVEL OBTER VALOR DO CAMPO DO ZABBIX: $campos[0] ";
$campos[1]="";
$erro=1;
}else{
print FILE "\n ---> CAMPO: $campos[0] \t VALOR: ";
print FILE uc remove_acentos($campos[1]);
$zabbix{$campos[0]} = uc remove_acentos($campos[1]);
}
}
if (!$zabbix{ATIVIDADE}){$mensagem .="\n ERRO na categorizacao - campo ATIVIDADE nao informado ";$erro=1;}
if (!$zabbix{SERVICO}){$mensagem .="\n ERRO na categorizacao - campo SERVICO nao informado ";$zabbix{SERVICO}='SERVIDOR';$erro=1;}
if (!$zabbix{PROCEDIMENTO}){$mensagem .="\n ERRO na categorizacao - campo PROCEDIMENTO nao informado ";$erro=1;}
if (!$zabbix{DESCRICAO}){$mensagem .="\n ERRO na categorizacao - campo DESCRICAO nao informado ";$erro=1;}
if (!$zabbix{CONTRATO}){$mensagem .="\n ERRO na categorizacao - campo CONTRATO nao informado ";$erro=1;}
if (!$zabbix{STATUS}){$mensagem .="\n ERRO na categorizacao - campo STATUS nao informado ";$erro=1;}
if (!$zabbix{TRIGGER}){$mensagem .="\n ERRO na categorizacao - campo TRIGGER nao informado ";$erro=1;}
if (!$zabbix{SEVERIDADE}){$mensagem .="\n ERRO na categorizacao - campo SEVERIDADE nao informado ";$erro=1;}
if (!$zabbix{ITEM_NAME}){$mensagem .="\n ERRO na categorizacao - campo ITEM_NAME nao informado ";$erro=1;}
if (!$zabbix{NOME_MONITORACAO}){$mensagem .="\n ERRO na categorizacao - campo NOME_MONITORACAO nao informado ";$erro=1;}
if (!$zabbix{EVENTO_ID}){$mensagem .="\n ERRO na categorizacao - campo EVENTO_ID nao informado ";$erro=1;}
if (!$zabbix{TRIGGER_ID}){$mensagem .="\n ERRO na categorizacao - campo TRIGGER_ID nao informado ";$erro=1;}
if (!$zabbix{ORIGEM}){$mensagem .="\n ERRO na categorizacao - campo ORIGEM nao informado ";$erro=1;}
if ($zabbix{CONTRATO} eq "*UNKNOWN*"){$mensagem .="\n ERRO na categorizacao - campo CONTRATO nao informado ";$erro=1;}
if (!$zabbix{COD_PROCEDIMENTO}){$mensagem .="\n ERRO na categorizacao - campo COD_PROCEDIMENTO nao informado ";$erro=1;}
########################
# DADOS PARA A CONEXAO #
########################
my $soap_user = "USER" ;
my $soap_password = "SENHA" ;
####################
# DADOS DO CHAMADO #
####################
my $open_subject = "PROBLEM" ;
#my $open_queue = "HOMOLOGACAO_MONITORACAO" ;
my $open_queue = "Operação" ;
my $lock = "unlock" ;
my $priority = "3 normal" ;
my $open_state = "Aberto" ;
my $mail_customer = "XXX.XXX\@XXXX.com.br" ;
my $open_user = 00;
my $open_owner = 00;
my $close_user = 00;
my $responsible = "XXX.XXX\@XXXX.com.br";
my $mail_from = "XXX.XXX\@XXXX.com.br" ;
my $mail_to ="XXX.XXX\@XXXX.com.br" ;
my $user_id = 00;
my $close_state = "Contigenciado";
my $close_subject = "OK";
my $empresa = "$zabbix{CONTRATO}";
my $servico = "$zabbix{SERVICO}";
my $atividade = "$zabbix{ATIVIDADE}";
my $hostname = "$zabbix{ORIGEM} - $zabbix{NOME_MONITORACAO}";
my $trigger_name = "$zabbix{TRIGGER_ID}-$zabbix{TRIGGER}";
my $tID = "$zabbix{TRIGGER_ID}";
my $trigger_subject = $zabbix{STATUS};
my $description = "$zabbix{DESCRICAO}";
my $trigger_body = "";
if ($erro==1){
$mensagem .="\n\n Este erro ocorreu na TRIGGER: $trigger_name";
$mensagem .="\n Na monitoracao : $hostname";
# EnviaEmail();
print FILE "\nEnviado e-mail avisando de provahveis erros na trigger.\n";
}
####################
# CORPO DO CHAMADO #
####################
my $campo;
my $dado;
$trigger_body="\n DADOS ORIUNDOS DA MONITORAÇÃO \n";
while (($campo,$dado) = each %zabbix ){
$trigger_body=$trigger_body."\n $campo: \t\t $dado";
}
################################
# CRIANDO A CONEXAO COM O OTRS #
################################
use SOAP::Lite('autodispatch', proxy => "http://XXXXX.com.br/otrs/rpc.pl");
my $rpc_connect = Core->new() ;
##########################
# ABERTURA OU FECHAMENTO #
##########################
print FILE "\n\nTRIGGER E SUBJECT: SUBJETC:$trigger_subject|OPEN:$open_subject|CLOSE:$close_subject\n ";
if ( $trigger_subject eq $open_subject ) {
# my @ticket_ids = search_ticket($hostname, $tID) ;
my @ticket_ids = busca_interna($hostname, $tID) ;
unless (@ticket_ids ) {
print FILE "\n INCIANDO MÉTODO PARA ABERTURA DO CHAMADO\n";
open_ticket( $hostname, $tID);
print FILE "\n FINALIZADO MÉTODO PARA ABERTURA DA CHAMADO\n";
}else{
if (@ticket_ids){
print FILE "\n Iniciando método para atualizacao do chamado";
# atualiza_ticket(@ticket_ids);
print FILE "\n Finalizado o método de atualização";
}
}
}
if ( $trigger_subject eq $close_subject ) {
# my @ticket_ids = search_ticket($hostname, $tID) ;
my @ticket_ids = busca_interna($hostname, $tID) ;
if (@ticket_ids) {
print FILE "\nINCIANDO MÉTODO PARA FECHAMENTO DE CHAMADO\n";
close_ticket(@ticket_ids);
print FILE "\nFINALIZADO O MÉTODO PARA FECHAMENTO DE CHAMADO\n";
}
}
###############
# FINALIZANDO #
###############
$dbh->disconnect();
print FILE "\n-------------FIM NORMALIZADO---------------\n";
close FILE;
sub EnviaEmail{
my $title='ERRO NA CONFIGURACAO ZABBIX';
my $to='YYYY@XXXXX.com.br';
my $from= 'ZZZZZ@XXXX.com.br';
my $subject='ERRO NA CONFIGURACAO ZABBIX';
open(MAIL, "|/usr/sbin/sendmail -t");
print MAIL "To: $to\n";
print MAIL "From: $from\n";
print MAIL "Subject: $subject\n\n";
print MAIL "$mensagem";
close(MAIL);
}
######################################
# FUNCOES PARA ABERTURA E FECHAMENTO #
######################################
sub open_ticket {
my ( $hostname, $tID ) = @_ ;
my $ticket_number = $rpc_connect->Dispatch( $soap_user, $soap_password, 'TicketObject','TicketCreateNumber');
my %ticket_data = (
TN => $ticket_number,
Title => "$hostname: $tID",
Queue => $open_queue,
Lock => $lock,
Priority => $priority,
TypeID => 16,
State => $open_state,
Customer => $mail_customer,
CustomerID => $empresa,
CustomerUser => $mail_customer,
OwnerID => $open_owner,
UserID => $open_owner,
Responsible => $responsible,
Service => $servico,
SLA => $atividade,
) ;
my $ticket_id = $rpc_connect->Dispatch( $soap_user, $soap_password, 'TicketObject', 'TicketCreate', %ticket_data ) ;
die "\nTicket nao foi aberto!.\n" if !defined $ticket_id;
print FILE "\n Criado ticket - $ticket_id";
my %article_data = (
TicketID => $ticket_id,
ArticleType => 'email-internal',
SenderType => 'agent',
Subject => "$hostname: $tID",
Body => $trigger_body,
ContentType => 'text/plain; UTF-8',
HistoryType => 'AddNote',
HistoryComment => 'Auto Ticket',
UserID => 00,
NoAgentNotify => 1,
);
$rpc_connect->Dispatch( $soap_user, $soap_password, 'TicketObject', 'ArticleCreate', %article_data) ;
print FILE "\n Criado NOTA no ticket - $ticket_id";
#######################
# DEFININDO O SERVICO #
#######################
# print FILE "\n Servico ($servico) sendo definido para o $ticket_id";
# %ticket_data = (
# TicketID => $ticket_id,
# UserID => 00,
# Service => "$servico",
# ) ;
# my $sucesso_servico = $rpc_connect->Dispatch( $soap_user, $soap_password, 'TicketObject', 'TicketServiceSet', %ticket_data ) ;
# die "\nServico nao definido!.\n" if !defined $sucesso_servico;
# print FILE "\n Servico definido - $ticket_id";
#########################
# DEFININDO A ATIVIDADE #
#########################
# print FILE "\n Atividade ($atividade) sendo definida - $ticket_id";
# %ticket_data = (
# TicketID => $ticket_id,
# UserID => 00,
# SLA => "$atividade",
# ) ;
# my $sucesso_atividade = $rpc_connect->Dispatch( $soap_user, $soap_password, 'TicketObject', 'TicketSLASet', %ticket_data ) ;
# die "\nAtividade nao definida!.\n" if !defined $sucesso_atividade;
# print FILE "\n Atividade definida - $ticket_id";
#
#
# %article_data = (
# TicketID => $ticket_id,
# ArticleType => 'email-internal',
# SenderType => 'agent',
# Subject => "DADOS PARA PROCEDIMENTO",
# Body => $nota_procedimento,
# ContentType => 'text/plain; UTF-8',
# HistoryType => 'AddNote',
# HistoryComment => 'Auto Ticket',
# UserID => 00,
# NoAgentNotify => 1,
# );
# $rpc_connect->Dispatch( $soap_user, $soap_password, 'TicketObject', 'ArticleCreate', %article_data) ;
# print FILE "\n Criado NOTA no ticket - $ticket_id";
#
print FILE "\n INICIANDO armazenamento do ticket id localmente";
$dbh->do("INSERT INTO t_chamados VALUES ($ticket_id,'$hostname: $tID')")or die "Não foi possível realizar insert: $DBI::errstr";
$dbh->commit()or die "Não foi possível realizar commit: $DBI::errstr";
print FILE "\n FINALIZANDO armazenamento do ticket id localmente";
}
sub search_ticket {
print FILE "\nINICIALIZANDO FUNCAO DE BUSCA DE TICKETS\n";
my ( $hostname, $tID ) = @_ ;
print FILE "\nBUSCANDO: $hostname, $tID \n";
my %ticket_filter = (
Result => 'ARRAY' || 'HASH' || 'COUNT',
StateType => ['open','new'],
UserID => $open_user,
ContentSearch => 'AND',
Title => "$hostname: $tID",
) ;
my @found_ticket_ids = $rpc_connect->Dispatch( $soap_user, $soap_password, 'TicketObject', 'TicketSearch', %ticket_filter ) ;
foreach (@found_ticket_ids){
print FILE "\n ENCONTRADO: $_ \n";
}
print FILE "\nFINALIZANDO BUSCA DE TICKETS\n";
return @found_ticket_ids ;
}
sub busca_interna {
print FILE "\nINICIALIZANDO NOVA FUNCAO DE BUSCA DE TICKETS\n";
my ( $hostname, $tID ) = @_ ;
print FILE "\nSELECT chamado FROM t_chamados WHERE identificador = '$hostname: $tID'\n";
my $sql = "SELECT chamado FROM t_chamados WHERE identificador = '$hostname: $tID'";
my $sel = $dbh->prepare($sql);
$sel->execute;
my $chamado;
my $rv = $sel->bind_columns(\$chamado);
my @found_ticket_ids;
while ($sel->fetch) {
push(@found_ticket_ids, $chamado);
}
# push(@coins, "Penny");
foreach (@found_ticket_ids){
print FILE "\n ENCONTRADO: $_ \n";
}
print FILE "\nFINALIZANDO NOVA BUSCA DE TICKETS\n";
return @found_ticket_ids ;
}
sub close_ticket {
my @ticket_ids = @_ ;
foreach my $ticket_id (@ticket_ids) {
my %article_data = (
TicketID => $ticket_id,
ArticleType => 'note-internal',
SenderType => 'agent',
Subject => "FERRAMENTA DE MONITORACAO - CONTIGENCIAMENTO",
Body => 'Este evento normalizou na ferramenta da monitoracao. Chamado contigenciado para ser investigada a causa raiz.',
ContentType => 'text/plain; UTF-8',
HistoryType => 'StateUpdate',
HistoryComment => 'CHAMADO CONTIGENCIADO PELA FERRAMENTA DE MONITORAÇÃO.',
UserID => 00,
NoAgentNotify => 1,
);
my %unLOCK = (
Lock => 'unlock',
TicketID => $ticket_id,
UserID => 00,
);
$rpc_connect->Dispatch( $soap_user, $soap_password, 'TicketObject', 'TicketLockSet', %unLOCK) ;
my %ticket_status = (
State => "Em Execução",
UserID => 00,
TicketID => $ticket_id,
);
$rpc_connect->Dispatch( $soap_user, $soap_password, 'TicketObject', 'ArticleCreate', %article_data) ;
$rpc_connect->Dispatch( $soap_user, $soap_password, 'TicketObject', 'TicketStateSet', %ticket_status) ;
my %ticket_status2 = (
StateID => 15,
UserID => 00,
TicketID => $ticket_id,
);
$rpc_connect->Dispatch( $soap_user, $soap_password, 'TicketObject', 'TicketStateSet', %ticket_status2 );
print FILE "\nAPAGANDO TICKET DA BASE LOCAL\n";
$dbh->do("DELETE FROM t_chamados WHERE chamado=$ticket_id")or die "Não foi possível realizar o delete: $DBI::errstr";
$dbh->commit()or die "Não foi possível realizar commit: $DBI::errstr";
print FILE "\nAPAGADO TICKET DA BASE LOCAL\n";
}
}
sub atualiza_ticket {
my @ticket_ids = @_ ;
foreach my $ticket_id (@ticket_ids) {
my %article_data = (
TicketID => $ticket_id,
ArticleType => 'note-internal',
SenderType => 'agent',
Subject => "ESTADO DO ALARME NA FERRAMENTA DE MONITORACAO.",
Body => 'O EVENTO CONTINUA ATIVO NA FERRAMENTA DE MONITORACAO.',
ContentType => 'text/plain; UTF-8',
HistoryType => 'AddNote',
HistoryComment => 'Evento ainda ativo na ferramenta de monitoracao',
UserID => 00,
NoAgentNotify => 1,
);
$rpc_connect->Dispatch( $soap_user, $soap_password, 'TicketObject', 'ArticleCreate', %article_data) ;
#my %ticket_status = (
#State => $close_state,
#UserID => $close_user,
#TicketID => $ticket_id,
#);
#$rpc_connect->Dispatch( $soap_user, $soap_password, 'TicketObject', 'TicketStateSet', %ticket_status );
}
}
sub remove_acentos {
my $string = shift;
$string =~ tr/A-Z/a-z/;
my @comacentos = ('á','â','ã','é','ê','í','ó','õ','ô','ú','ü','ç');
my @semacentos = ('a','a','a','e','e','i','o','o','o','u','u','c');
my $item = 0;
my $size_acentos = @comacentos;
while ($item < $size_acentos){
if ($string =~ m/$comacentos[$item]/g){
$string =~ s/$comacentos[$item]/$semacentos[$item]/g;
}
$item++;
}
$string =~ s/^\s+//;
$string =~ s/\s+$//;
return $string;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment