Herramientas de usuario

Herramientas del sitio


manuales:nagios:capacitacion:tipos_de_notificaciones

Diferencias

Muestra las diferencias entre dos versiones de la página.

Enlace a la vista de comparación

Ambos lados, revisión anteriorRevisión previa
Próxima revisión
Revisión previa
manuales:nagios:capacitacion:tipos_de_notificaciones [2016/07/14 14:47] – [Definiciones previas] cayumanuales:nagios:capacitacion:tipos_de_notificaciones [2019/03/26 20:25] (actual) – [Telegram] cayu
Línea 1: Línea 1:
 ====== Tipos de notificaciones ====== ====== Tipos de notificaciones ======
 ==== Definiciones previas  ==== ==== Definiciones previas  ====
-**Indicador**: //Dato o información que sirve para conocer o valorar las características y la intensidad de un hecho o para determinar su evolución futura.// +  * **Indicador**: //Dato o información que sirve para conocer o valorar las características y la intensidad de un hecho o para determinar su evolución futura.// 
- +  **Alerta**: //Señal o aviso con el objetivo de desviar la atención hacia el dato obtenido del indicador.// 
-**Alerta**: //Señal o aviso con el objetivo de desviar la atención hacia el dato obtenido del indicador.// +  **Notificación**: //Hacer saber una cosa a alguien siguiendo ciertas formalidades.// 
- +  **Criterio**: //Opinión, juicio o decisión que se adopta sobre una cosa.//
-**Notificación**: //Hacer saber una cosa a alguien siguiendo ciertas formalidades.// +
- +
-**Criterio**: //Opinión, juicio o decisión que se adopta sobre una cosa.//+
  
  
Línea 125: Línea 122:
 {{:manuales:nagios:nagios_sms.svg.gz|}} {{:manuales:nagios:nagios_sms.svg.gz|}}
 ===== WhatsApp (Dependencia externa sin garantía) ===== ===== WhatsApp (Dependencia externa sin garantía) =====
 +  * https://github.com/tgalal/yowsup
 ===== Telegram ===== ===== Telegram =====
 +<code python>
 +#!/usr/bin/env python
 +
 +import argparse
 +from twx.botapi import TelegramBot
 +
 +def parse_args():
 +    parser = argparse.ArgumentParser(description='Nagios notification via Telegram')
 +    parser.add_argument('-t', '--token', nargs='?', required=True)
 +    parser.add_argument('-o', '--object_type', nargs='?', required=True)
 +    parser.add_argument('--contact', nargs='?', required=True)
 +    parser.add_argument('--notificationtype', nargs='?')
 +    parser.add_argument('--hoststate', nargs='?')
 +    parser.add_argument('--hostname', nargs='?')
 +    parser.add_argument('--hostaddress', nargs='?')
 +    parser.add_argument('--servicestate', nargs='?')
 +    parser.add_argument('--servicedesc', nargs='?')
 +    parser.add_argument('--output', nargs='?')
 +    args = parser.parse_args()
 +    return args
 +
 +def send_notification(token, user_id, message):
 +    bot = TelegramBot(token)
 +    bot.send_message(user_id, message).wait()
 +
 +def host_notification(args):
 +    state = ''
 +    if args.hoststate == 'UP':
 +        state = u'\U00002705 '
 +    elif args.hoststate == 'DOWN':
 +        state = u'\U0001F525 '
 +    elif args.hoststate == 'UNREACHABLE':
 +        state = u'\U00002753 '
 +
 +    return "%s%s (%s): %s" % (
 +        state,
 +        args.hostname,
 +        args.hostaddress,
 +        args.output,
 +    )
 +
 +def service_notification(args):
 +    state = ''
 +    if args.servicestate == 'OK':
 +        state = u'\U00002705 '
 +    elif args.servicestate == 'WARNING':
 +        state = u'\U000026A0 '
 +    elif args.servicestate == 'CRITICAL':
 +        state = u'\U0001F525 '
 +    elif args.servicestate == 'UNKNOWN':
 +        state = u'\U00002753 '
 +
 +    return "%s%s/%s: %s" % (
 +        state,
 +        args.hostname,
 +        args.servicedesc,
 +        args.output,
 +    )
 +
 +def main():
 +    args = parse_args()
 +    user_id = int(args.contact)
 +    if args.object_type == 'host':
 +        message = host_notification(args)
 +    elif args.object_type == 'service':
 +        message = service_notification(args)
 +    send_notification(args.token, user_id, message)
 +
 +if __name__ == '__main__':
 +    main()
 +</code>
 +  * https://github.com/pommi/telegram_nagios
 +<code php>
 +#!/usr/bin/php -q
 +<?php
 +// Example: php /usr/local/nagios/sbin/telegram-notify/telegram-bot.php "370022700" "83633434:kewkekekekdkkfiirrjririrjr" 1 "Notify: NOTIFICATIONTYPE 0XzXZ0 Host: HOSTNAME 0XzXZ0 Service: SERVICEDESC 0XzXZ0 Date: SHORTDATETIME 0XzXZ0 Info: SERVICEOUTPUT"
 +// Using to send messages about new threads in moderated status.
 +// where 370022700 - chat_id.
 +//
 +/*
 +Bot: nagiosnotifybot
 +API:83633434:kewkekekekdkkfiirrjririrjr
 +-----
 +How to get Chat_ID or Username of Telegram channel/chat:
 +1. Add bot to chat/channel as admin with post messages permitions.
 +2. Type command /my_id in chat.
 +3. See output here: https://api.telegram.org/bot83633434:kewkekekekdkkfiirrjririrjr/getUpdates
 +----
 +*/
 +//date_default_timezone_set('Europe/Minsk');
 +ini_set('display_errors', 1);
 +ini_set('display_startup_errors', 1);
 +error_reporting(E_ALL ^ E_NOTICE);
 +set_time_limit(30);
 +define('THIS_SCRIPT', 'telegram-bot');
 +
 +$chat_id = $argv[1];
 +$botToken = $argv[2];
 +$flag = $argv[3];
 +$message = $argv[4];
 +
 +//############## LOGS ####################//
 +$log_file= __DIR__ . '/log/'.date('dmY').'_telegram.log';
 +
 +if(!file_exists ($log_file))
 + {
 +$fh = fopen ($log_file, "w+");
 +  fwrite ($fh, "");
 +  fclose ($fh);
 + }
 +//##################################//
 +
 +if (isset($flag))
 +{
 + if ($flag != 1)
 + {
 + //$msg = 'Flag is NOT valid: ' .$flag.' Exit.';
 + //echo $msg."\n";
 + //file_put_contents($log_file,date('d.m.Y H:i:s').'  :    '.$msg."\r\n",FILE_APPEND );
 + /**** Flag must be = 1. ****/
 + die;
 + }
 +} else{
 + //$msg = 'Not input flag: ' .$flag.' Exit.';
 + //echo $msg."\n";
 + //file_put_contents($log_file,date('d.m.Y H:i:s').'  :    '.$msg."\r\n",FILE_APPEND );
 + die;
 +}
 +
 +$msg = "-------------------------------------------------------------------";
 +file_put_contents($log_file,$msg."\r\n",FILE_APPEND );
 +
 +/* Debug
 +$msg = "----- DEBUG:\nChat_id: ".$chat_id. ".\nBot_token: ".$botToken.".\nFlag: ".$flag.".\nMessage: ".$message."\n    ----- DEBUG.";
 +file_put_contents($log_file,date('d.m.Y H:i:s').'  :    '.$msg."\r\n",FILE_APPEND );
 +Debug */
 +
 +if (!$chat_id) 
 + {
 + $msg = 'Not input chat_id. Exit.'; 
 + echo $msg."\n";
 + file_put_contents($log_file,date('d.m.Y H:i:s').'  :    '.$msg."\r\n",FILE_APPEND );
 + die;
 + }
 +
 +if (!$botToken) 
 + {
 + $msg = 'Not input botToken. Exit.'; 
 + echo $msg."\n";
 + file_put_contents($log_file,date('d.m.Y H:i:s').'  :    '.$msg."\r\n",FILE_APPEND );
 + die;
 + }
 +
 +//Fix line break
 +// 0XzXZ0 - it's fake line break character defined in Nagios command definition.
 +function replace_linebreak($message)
 +{
 + global $message;
 + $linebreak = "\n";
 + $message = preg_replace('/0XzXZ0?/m', $linebreak, $message);
 + $message = urlencode($message);
 +    return $message;
 +}
 +
 +function Send_msg_to_Telegram ($botToken, $telegram_chat_id, $message){
 + global $url, $log_file;
 + $bot_url    = "https://api.telegram.org/bot$botToken/";
 + //Fix new break
 + $message = replace_linebreak($message);
 + $url = $bot_url."sendMessage?chat_id=".$telegram_chat_id."&text=".$message;
 + if ($content = json_decode(file_get_contents($url),true)) {
 + return $content['ok'];
 + }else{
 + $msg = "ERROR with Telegram chat: ".$telegram_chat_id.".";
 + echo $msg."\n";
 + file_put_contents($log_file,date('d.m.Y H:i:s').'  :    '.$msg."\r\n",FILE_APPEND );
 + }
 +}
 +
 +$TelegramGROUPS=explode(',',$chat_id);
 +
 +foreach ($TelegramGROUPS as $telegram_chat_id)
 +{
 + echo "\n";
 + $msg = '------------ START posting to '.$telegram_chat_id.' ------------';
 + echo $msg."\n";
 + file_put_contents($log_file,date('d.m.Y H:i:s').'  :    '.$msg."\r\n",FILE_APPEND );
 + $telegram_data = Send_msg_to_Telegram($botToken, $telegram_chat_id, $message);
 + if (isset($telegram_data) AND $telegram_data == 1) {
 + $msg = "Message was SENT to telegram ".$telegram_chat_id."\r\nText: ".$message;
 + echo $msg."\n";
 + file_put_contents($log_file,date('d.m.Y H:i:s').'  :    '.$msg."\r\n",FILE_APPEND );
 + } else {
 + $msg = "Message was NOT sent to telegram ".$telegram_chat_id."\r\nText: ".$message;
 + echo $msg."\n";
 + file_put_contents($log_file,date('d.m.Y H:i:s').'  :    '.$msg."\r\n",FILE_APPEND );
 + continue;
 + }
 +$msg = "------------ END posting to ".$telegram_chat_id." ------------";
 +echo $msg."\n";
 +file_put_contents($log_file,date('d.m.Y H:i:s').'  :    '.$msg."\r\n",FILE_APPEND );
 +}
 +
 +//Clean OLD logs every 30 days
 + $files = glob(realpath(dirname(__FILE__)).'/log/*.log');
 + if (empty($files)) {
 + exit;
 + }
 + foreach($files as $file){
 + if(time() - filectime($file) > 2592000){
 + unlink($file);
 + }
 +
 +//Clean OLD logs every 30 days
 +?>
 +</code>
 +https://exchange.nagios.org/directory/Addons/Notifications/Telegram-Notifications/details
 +<code ini>
 +# Host notification via Telegram bot
 +define command{
 +        command_name    notify-host-by-telegram
 +        command_line     curl -k -L --data chat_id=REPLACEME --data-urlencode "text=***** Nagios ***** Notification Type: $NOTIFICATIONTYPE$ Host: $HOSTNAME$ State: $HOSTSTATE$ Address: $HOSTADDRESS$ Info: $HOSTOUTPUT$ Date/Time: $LONGDATETIME$" "https://api.telegram.org/botREPLACEME/sendMessage"
 +        }
 +
 +# Service notification via Telegram bot
 +define command{
 +        command_name    notify-service-by-telegram
 +        command_line   curl -k -L --data chat_id=-REPLACEME --data-urlencode "text=***** Nagios ***** Notification Type: $NOTIFICATIONTYPE$ Service: $SERVICEDESC$ Host: $HOSTALIAS$ Address: $HOSTADDRESS$ State: $SERVICESTATE$ Date/Time: $LONGDATETIME$ Additional Info: $SERVICEOUTPUT$" "https://api.telegram.org/botREPLACEME/sendMessage"
 +        }
 +</code>
 +https://github.com/mglantz/nagios-telegram-notification
 ===== Visual general ===== ===== Visual general =====
  
manuales/nagios/capacitacion/tipos_de_notificaciones.1468507643.txt.gz · Última modificación: 2016/07/14 14:47 por cayu