Invio di notifiche Nagios con Telegram: Difference between revisions

From RVM Wiki
Jump to navigation Jump to search
 
(8 intermediate revisions by the same user not shown)
Line 12: Line 12:
* A questo punto si riceverà la il token del Bot, del tipo:
* A questo punto si riceverà la il token del Bot, del tipo:
   110201543:AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsaw
   110201543:AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsaw
* Da Telegram, '''inviare ora DUE MESSAGGI qualsiasi al BOT''' per inizializzarlo, altrimenti lo script python successivo darà errore.


==Installazione dello script di notifica==
* Esportare la variabile:
* Lo script già pronto ed agggiornato, contenente tutte le librerie si trova sul repository git, contentente tutte librerie necessarie. Il suo template è:
export BOT_TOKEN="110201543:AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsaw"
<pre>
#!/usr/bin/env python


import ConfigParser
* Installare i tool per testare:
import os
sudo apt-get install wget jq
import sys
libpath=os.path.expanduser('~') + "/nagios-telegram-bot/lib"
sys.path.append(libpath)
import telegram


conffile=os.path.expanduser('~') + "/nagios-telegram-bot.ini"
* Per rilevare il proprio chat_id, inviare un messaggio al bot dal proprio account Telegram, poi eseguire (sostutiendo la stringa corretta del BOT:
Config = ConfigParser.ConfigParser()
wget --quiet -O - https://api.telegram.org/bot${BOT_TOKEN}/getUpdates | jq
Config.read(conffile)
bot_token = Config.get("main", "token")
#print ("Token=%s" % bot_token)
bot = telegram.Bot(token=bot_token)
chat_id = bot.getUpdates()[-1].message.chat_id
message = sys.argv[1]
bot.sendMessage(chat_id=chat_id, text=message)
</pre>
* Diventare utente nagios e posizionarsi nella home directory
sudo -u nagios bash --login
cd
pwd


* Clonare lo script:
* Rilevare il valore "id" relativo al proprio username Telegram
git clone https://mnt.vvngrl@assistenza.rvmgroup.it/git/nagios-telegram-bot
 
* Inserire il token nel file di configurazione:
cp nagios-telegram-bot/nagios-telegram-bot.ini .
vi nagios-telegram-bot.ini


<pre>
<pre>
[main]
{
token=110201543:AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsaw
  "ok": true,
  "result": [
    {
      "update_id": 551287462,
      "message": {
        "message_id": 15,
        "from": {
          "id": 39520274,
          "is_bot": false,
          "first_name": "Gabriele",
          "last_name": "Vivinetto",
          "username": "GabrieleV",
          "language_code": "en"
        },
        "chat": {
          "id": 39520274,
          "first_name": "Gabriele",
          "last_name": "Vivinetto",
          "username": "GabrieleV",
          "type": "private"
        },
        "date": 1513163622,
        "text": "test"
      }
    }
  ]
}
</pre>
</pre>


* Testare l'invio di un messaggio:
* In questo caso il chat_id dell'utente GabrieleV è il seguente, da esportare:
  nagios-telegram-bot/nagios-telegram-bot.py "Messaggio di test ore 15:06"
export CHAT_ID="39520274"
 
* Provare ad inviare un messaggio di test in questo modo, sostituendo il corretto bot_id e chat_id:
 
/usr/bin/wget --quiet -O - "https://api.telegram.org/bot${BOT_TOKEN}/sendMessage?chat_id=${CHAT_ID}&text=MESSAGGIO" | jq


* Il messaggio dovrebbe essere ricevuto dal Bot.
Questo è il risultato, e si deve ricevere il messaggio dal bot sul proprio account telegram:


* In nagios si configurerà un solo contatto dinotifica, quello che richiama lo script del bot
<pre>
* Chi vorrà ricevere i messaggi del Bot, dovrà iscriversi al Bot
{
  "ok": true,
  "result": {
    "message_id": 17,
    "from": {
      "id": 411087449,
      "is_bot": true,
      "first_name": "NagiosMetBot",
      "username": "NagiosMetBot"
    },
    "chat": {
      "id": 39520274,
      "first_name": "Gabriele",
      "last_name": "Vivinetto",
      "username": "GabrieleV",
      "type": "private"
    },
    "date": 1513164983,
    "text": "MESSAGGIO"
  }
}
</pre>


==Configurazione di Nagios==
==Configurazione di Nagios==


* Assicurarsi che la variabile HOME che punta alla home di nagios sia impostata al valore rilevato precedentemente:
* Definire il proprio contatto da usare solo per Telegram, impostando il proprio chat_id nel campo pager:


  sudoedit /etc/default/nagios3
  sudoedit /etc/nagios3/conf.d/contacts.cfg
 
<pre>
define contact{
    contact_name                    gabriele.vivinetto.telegram
    alias                          Gabriele Vivinetto Telegram
    email                          gabriele.vivinetto@example.com
    pager                          39520274
    service_notification_period    24x7
    host_notification_period        24x7
    service_notification_options    w,u,c,r
    host_notification_options      d,u,r
    host_notification_commands      notify-host-by-telegram-bot 
    service_notification_commands  notify-service-by-telegram-bot
}


export HOME="/var/log/nagios"
</pre>


* Definire il contact group:
* Definire il contact group:
Line 78: Line 118:
     contactgroup_name              nagios-admins-telegram
     contactgroup_name              nagios-admins-telegram
     alias                          Nagios Administrators Telegram
     alias                          Nagios Administrators Telegram
     members                        telegram-bot
     members                        gabriele.vivinetto.telegram
}
}
</pre>
</pre>


* Definire il contatto del Bot ed aggiungere i comandi di notifica (notare che il bot non ha ne indirizzo email, ne pager):


sudoedit /etc/nagios3/conf.d/contacts.cfg
* Definire i comandi di notifica, impostando il corretto bot_id
 
<pre>
define contact{
    contact_name                    telegram-bot
    alias                          Nagios Telegram Bot
    host_notification_period        24x7
    service_notification_period    24x7
    host_notification_options      d,r
    service_notification_options    w,c,r,u
    host_notification_commands      notify-host-by-telegram
    service_notification_commands  notify-service-by-telegram
}
</pre>


* Definire i comandi di notifica (per i percorsi, verificare la hom directory di nagios dove si è installato lo script):
  sudoedit /etc/nagios3/conf.d/notify_by_telegram_bot.cfg
  sudoedit /etc/nagios3/conf.d/commands.cfg


<pre>
<pre>
define command{
define command{
    command_name   notify-host-by-telegram
      command_name     notify-host-by-telegram-bot
    command_line    /var/log/nagios/nagios-telegram-bot/nagios-telegram-bot.py "$HOSTNAME$ $HOSTSTATE$ ($SHORTDATETIME$) $NOTIFICATIONTYPE$ $NOTIFICATIONCOMMENT$"
      command_line    /usr/bin/wget --quiet -O - "https://api.telegram.org/bot411087449:AAH3_Ftaw3B4_jQnNQWxMVpieOjmpg_7djs/sendMessage?chat_id=$CONTACTPAGER$&text=$HOSTNAME$%20$HOSTSTATE$%20($SHORTDATETIME$)%20$NOTIFICATIONTYPE$%20$NOTIFICATIONCOMMENT$"
}
}


define command{
define command{
    command_name   notify-service-by-telegram
      command_name     notify-service-by-telegram-bot
    command_line    /var/log/nagios/nagios-telegram-bot/nagios-telegram-bot.py "$HOSTNAME$/$SERVICEDESC$ $SERVICESTATE$ ($SHORTDATETIME$) $NOTIFICATIONTYPE$ $NOTIFICATIONCOMMENT$"
      command_line    /usr/bin/wget --quiet -O - "https://api.telegram.org/bot411087449:AAH3_Ftaw3B4_jQnNQWxMVpieOjmpg_7djs/sendMessage?chat_id=$CONTACTPAGER$&text=$HOSTNAME$/$SERVICEDESC$%20$SERVICESTATE$%20($SHORTDATETIME$)%20$NOTIFICATIONTYPE$%20$NOTIFICATIONCOMMENT$"
}
}
</pre>
</pre>
Line 141: Line 166:
</pre>
</pre>


* Definire gli host e servizi che dovranno essere notifiati, usando i templates appena creati:
* Definire gli host e servizi che dovranno essere notificati, usando i templates appena creati:


<pre>
<pre>
Line 169: Line 194:
=Tramite telegram-cli=
=Tramite telegram-cli=
==Installazione telegram-cli==
==Installazione telegram-cli==
Instllare con uno dei due metodi:
Instllare con uno dei tre metodi:
 
===Installazione con pacchetto Debian===
 
* Prelevare i sorgenti:
<pre>
cd /tmp/
git clone --recursive https://github.com/vysheng/tg.git &&  cd tg
</pre>
 
* Installare i tools e le dipendenze necessarie:
sudo apt-get install autotools-dev autoconf-archive libreadline-dev libconfig-dev libssl-dev lua5.1 liblua5.1-dev lua-lgi libevent-dev debhelper libreadline-dev libconfig-dev libssl-dev lua5.2 liblua5.2-dev libevent-dev libjansson-dev
 
* Compilare il pacchetto:
dpkg-buildpackage -b -rfakeroot
 
* Per installarlo localmente:
sudo dpkg -i ../telegram-cli_1.0.6-1_amd64.deb


===Installazione da sorgente===
===Installazione da sorgente===


===Debian Squeeze===
====Debian Squeeze====
* Installare le souce lts e backports
* Installare le souce lts e backports
* Installare le build-deps
* Installare le build-deps
  sudo apt-get install libreadline-dev libconfig-dev libssl-dev lua5.1 liblua5.1-0-dev libevent-dev libjansson-dev make git
  sudo apt-get install libreadline-dev libconfig-dev libssl-dev lua5.1 liblua5.1-0-dev libevent-dev libjansson-dev make git


===Debian Wheezy===
====Debian Wheezy====
* Installare le build-deps
* Installare le build-deps
  sudo apt-get install libreadline-dev libconfig-dev libssl-dev lua5.2 liblua5.2-dev libevent-dev libjansson-dev  
  sudo apt-get install libreadline-dev libconfig-dev libssl-dev lua5.2 liblua5.2-dev libevent-dev libjansson-dev  


===Debian===
====Debian====
<pre>
<pre>
cd /tmp/
cd /tmp/
Line 202: Line 244:
cp server.pub /etc/telegram-cli/server.pub
cp server.pub /etc/telegram-cli/server.pub
</pre>
</pre>
===Debian Squeeze===
====Debian Squeeze====
* Installare le librerie necessarie:
* Installare le librerie necessarie:
  sudo apt-get install libjansson4 libconfig8 liblua5.1-0
  sudo apt-get install libjansson4 libconfig8 liblua5.1-0


===Debian Wheezy===
====Debian Wheezy====
* Installare le librerie necessarie:
* Installare le librerie necessarie:
  sudo apt-get install libjansson4 libconfig9 liblua5.2-0
  sudo apt-get install libjansson4 libconfig9 liblua5.2-0
Line 218: Line 260:
to=$1
to=$1
msg=$2
msg=$2
tgpath=/usr/local/bin
tgpath=/usr/bin
nagios_home=/var/lib/nagios
#echo "$(date) - ID=$(id) - ${tgpath}/telegram-cli -C -R -W -p /var/log/nagios/.telegram-cli -c /var/log/nagios/.telegram-cli/config -e  \"msg $to $msg\"" >> /tmp/telegram-msg.log 2>&1
#echo "$(date) - ID=$(id) - ${tgpath}/telegram-cli -C -R -W -p /var/log/nagios/.telegram-cli -c /var/log/nagios/.telegram-cli/config -e  \"msg $to $msg\"" >> /tmp/telegram-msg.log 2>&1
${tgpath}/telegram-cli -C -R -W -p /var/log/nagios/.telegram-cli -c /var/log/nagios/.telegram-cli/config -e "msg $to $msg" # >> /tmp/telegram-msg.log 2>&1
${tgpath}/telegram-cli -C -R -W -p ${nagios_home}/.telegram-cli -c ${nagios_home}/.telegram-cli/config -e "msg $to $msg" # >> /tmp/telegram-msg.log 2>&1
</pre>
</pre>


Line 257: Line 300:
  sudoedit /etc/default/nagios3
  sudoedit /etc/default/nagios3


  export HOME="/var/log/nagios"
  export HOME="/var/lib/nagios"


* Definire il proprio nome Telegram nel campo pager del contact nagios ed aggiunger ei comandi di notifica::
* Definire il proprio nome Telegram nel campo pager del contact nagios ed aggiunger ei comandi di notifica::

Latest revision as of 14:25, 14 December 2017

Tramite Bot

L'utilizzo di un Bot evita di dover creare un account telegram fittizio.

Creazione del Bot

  • Da un account Telegram qualsiasi, aggiungere il bot BotFather, cliccando sul link [1]
  • Scrivere il comando
/newbot
  • Alla domanda, inserire il nome descrittivo del Bot, ad esempio
My Example Bot
  • Alla domanda, inserire lo username del Bot, che dovrà terminare in "bot", ad esempio
my-example-bot
  • A questo punto si riceverà la il token del Bot, del tipo:
 110201543:AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsaw
  • Esportare la variabile:
export BOT_TOKEN="110201543:AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsaw"
  • Installare i tool per testare:
sudo apt-get install wget jq
  • Per rilevare il proprio chat_id, inviare un messaggio al bot dal proprio account Telegram, poi eseguire (sostutiendo la stringa corretta del BOT:
wget --quiet -O - https://api.telegram.org/bot${BOT_TOKEN}/getUpdates | jq 
  • Rilevare il valore "id" relativo al proprio username Telegram
{
  "ok": true,
  "result": [
    {
      "update_id": 551287462,
      "message": {
        "message_id": 15,
        "from": {
          "id": 39520274,
          "is_bot": false,
          "first_name": "Gabriele",
          "last_name": "Vivinetto",
          "username": "GabrieleV",
          "language_code": "en"
        },
        "chat": {
          "id": 39520274,
          "first_name": "Gabriele",
          "last_name": "Vivinetto",
          "username": "GabrieleV",
          "type": "private"
        },
        "date": 1513163622,
        "text": "test"
      }
    }
  ]
}
  • In questo caso il chat_id dell'utente GabrieleV è il seguente, da esportare:
export CHAT_ID="39520274"
  • Provare ad inviare un messaggio di test in questo modo, sostituendo il corretto bot_id e chat_id:
/usr/bin/wget --quiet -O - "https://api.telegram.org/bot${BOT_TOKEN}/sendMessage?chat_id=${CHAT_ID}&text=MESSAGGIO" | jq

Questo è il risultato, e si deve ricevere il messaggio dal bot sul proprio account telegram:

{
  "ok": true,
  "result": {
    "message_id": 17,
    "from": {
      "id": 411087449,
      "is_bot": true,
      "first_name": "NagiosMetBot",
      "username": "NagiosMetBot"
    },
    "chat": {
      "id": 39520274,
      "first_name": "Gabriele",
      "last_name": "Vivinetto",
      "username": "GabrieleV",
      "type": "private"
    },
    "date": 1513164983,
    "text": "MESSAGGIO"
  }
}

Configurazione di Nagios

  • Definire il proprio contatto da usare solo per Telegram, impostando il proprio chat_id nel campo pager:
sudoedit /etc/nagios3/conf.d/contacts.cfg
define contact{
    contact_name                    gabriele.vivinetto.telegram
    alias                           Gabriele Vivinetto Telegram
    email                           gabriele.vivinetto@example.com
    pager                           39520274
    service_notification_period     24x7
    host_notification_period        24x7
    service_notification_options    w,u,c,r
    host_notification_options       d,u,r
    host_notification_commands      notify-host-by-telegram-bot  
    service_notification_commands   notify-service-by-telegram-bot
}

  • Definire il contact group:
sudoedit /etc/nagios3/conf.d/contacts.cfg
define contactgroup{
    contactgroup_name               nagios-admins-telegram
    alias                           Nagios Administrators Telegram
    members                         gabriele.vivinetto.telegram
}


  • Definire i comandi di notifica, impostando il corretto bot_id
sudoedit /etc/nagios3/conf.d/notify_by_telegram_bot.cfg
define command{
      command_name      notify-host-by-telegram-bot
      command_line    /usr/bin/wget --quiet -O - "https://api.telegram.org/bot411087449:AAH3_Ftaw3B4_jQnNQWxMVpieOjmpg_7djs/sendMessage?chat_id=$CONTACTPAGER$&text=$HOSTNAME$%20$HOSTSTATE$%20($SHORTDATETIME$)%20$NOTIFICATIONTYPE$%20$NOTIFICATIONCOMMENT$"
}

define command{
      command_name      notify-service-by-telegram-bot
      command_line    /usr/bin/wget --quiet -O - "https://api.telegram.org/bot411087449:AAH3_Ftaw3B4_jQnNQWxMVpieOjmpg_7djs/sendMessage?chat_id=$CONTACTPAGER$&text=$HOSTNAME$/$SERVICEDESC$%20$SERVICESTATE$%20($SHORTDATETIME$)%20$NOTIFICATIONTYPE$%20$NOTIFICATIONCOMMENT$"
}
  • Definire i template di host che dovranno essere notificati via telegram (aggiungere oltre a nagios-admins-telegram anche tutti gli altri contact groups per le notifiche via mail)
sudoedit templates_hosts.cfg
define host{
    name                            telegram-host
    use                             generic-host
    notification_options            d,r
    contact_groups                  nagios-admins-telegram,nagios-admins
    register                        0
}
  • Definire i template di services che dovranno essere notificati via telegram (aggiungere oltre a nagios-admins-telegram anche tutti gli altri contact groups per le notifiche via mail)
sudoedit templates_services.cfg
define service{
    name                            telegram-service
    use                             generic-service
    contact_groups                  nagios-admins-telegram,nagios-admins
    notification_options            c,r
    register                        0
}

  • Definire gli host e servizi che dovranno essere notificati, usando i templates appena creati:
define host{
    use             telegram-host
    host_name       host.example.com
    alias           Wxample host
	# ...
}
define service{
    use                 telegram-service
    host_name           host.example.com
    service_description EXAMPLE_SERVICE
	# ....
}
  • Testare la configurazione e Riavviare nagios
sudo -u nagios /usr/sbin/nagios3 -v /etc/nagios3/nagios.cfg && sudo /etc/init.d/nagios3 restart
  • Inviare una notifica custom da web gui nagios

Riferimenti

Tramite telegram-cli

Installazione telegram-cli

Instllare con uno dei tre metodi:

Installazione con pacchetto Debian

  • Prelevare i sorgenti:
cd /tmp/
git clone --recursive https://github.com/vysheng/tg.git &&  cd tg
  • Installare i tools e le dipendenze necessarie:
sudo apt-get install autotools-dev autoconf-archive libreadline-dev libconfig-dev libssl-dev lua5.1 liblua5.1-dev lua-lgi libevent-dev debhelper libreadline-dev libconfig-dev libssl-dev lua5.2 liblua5.2-dev libevent-dev libjansson-dev 
  • Compilare il pacchetto:
dpkg-buildpackage -b -rfakeroot
  • Per installarlo localmente:
sudo dpkg -i ../telegram-cli_1.0.6-1_amd64.deb

Installazione da sorgente

Debian Squeeze

  • Installare le souce lts e backports
  • Installare le build-deps
sudo apt-get install libreadline-dev libconfig-dev libssl-dev lua5.1 liblua5.1-0-dev libevent-dev libjansson-dev make git

Debian Wheezy

  • Installare le build-deps
sudo apt-get install libreadline-dev libconfig-dev libssl-dev lua5.2 liblua5.2-dev libevent-dev libjansson-dev 

Debian

cd /tmp/
git clone --recursive https://github.com/vysheng/tg.git && cd tg
./configure 
make
sudo cp bin/telegram-cli /usr/local/bin
sudo mkdir /etc/telegram-cli/
sudo cp server.pub /etc/telegram-cli/server.pub

Installazione da binario

  • Compilare su una macchina uguale
  • Copiare il binario e le chiavi server
cp bin/telegram-cli /usr/local/bin
mkdir /etc/telegram-cli/
cp server.pub /etc/telegram-cli/server.pub

Debian Squeeze

  • Installare le librerie necessarie:
sudo apt-get install libjansson4 libconfig8 liblua5.1-0

Debian Wheezy

  • Installare le librerie necessarie:
sudo apt-get install libjansson4 libconfig9 liblua5.2-0

Creazione script

sudoedit /usr/local/bin/telegram-msg
#!/bin/bash
to=$1
msg=$2
tgpath=/usr/bin
nagios_home=/var/lib/nagios
#echo "$(date) - ID=$(id) - ${tgpath}/telegram-cli -C -R -W -p /var/log/nagios/.telegram-cli -c /var/log/nagios/.telegram-cli/config -e  \"msg $to $msg\"" >> /tmp/telegram-msg.log 2>&1
${tgpath}/telegram-cli -C -R -W -p ${nagios_home}/.telegram-cli -c ${nagios_home}/.telegram-cli/config -e "msg $to $msg" # >> /tmp/telegram-msg.log 2>&1
sudo chmod +x  /usr/local/bin/telegram-msg

Registrazione account

  • Occorre avere un numero di telefono a cui ricevere sms o ricevere chiamate
  • Diventare nagios
sudo -u nagios -s /bin/bash --login
cd
  • Registrarsi con il numero e inserire il codice
telegram-cli
...
phone number: +391234567
code ('call' for phone call): inserire il codice ricevuto per sms o scrivere call per farsi chiamare
  • Aggiungere il proprio contatto a cui si vogliono ricevere le notifiche
add_contact +123456789 Nome Cognome
  • Testare ATTENZIONE: sostituire lo spazio tra Nome e Cognome con "_"):
msg Nome_Cognome Messaggio da inviare
quit
  • Verificare la home directory di nagios
cd
pwd
  • Testare lo script (verificare che la home dir usata nello script sia quella giusta)
telegram-msg Nome_Cognome Messaggio da inviare

Configurazione di Nagios

  • Assicurarsi che la variabile HOME che punta alla hoe di nagios sia impostata al valore rilevato precedentemente:
sudoedit /etc/default/nagios3
export HOME="/var/lib/nagios"
  • Definire il proprio nome Telegram nel campo pager del contact nagios ed aggiunger ei comandi di notifica::
sudoedit /etc/nagios3/conf.d/contacts.cfg
define contact{
       # ...
       host_notification_commands	notify-host-by-email, notify-host-by-telegram
       service_notification_commands	notify-service-by-email, notify-service-by-telegram
       #...
       pager				Nome_Cognome
}
  • Definire i comandi di notifica:
sudoedit /etc/nagios3/conf.d/commands.cfg
# ...
define command{
	command_name	notify-host-by-telegram
	command_line	/usr/local/bin/telegram-msg  $CONTACTPAGER$ "--Nagios Host Notification-- Host: $HOSTNAME$, State: $HOSTSTATE$, Time: $LONGDATETIME$"
}

define command{
	command_name	notify-service-by-telegram
	command_line	/usr/local/bin/telegram-msg  $CONTACTPAGER$ "--Nagios Service Notification-- Host: $HOSTNAME$, State: $HOSTSTATE$ Service $SERVICEDESC$ Description: $SERVICESTATE$ Time: $LONGDATETIME$"
}
  • Testare la configurazione e Riavviare nagios
sudo -u nagios /usr/sbin/nagios3 -v /etc/nagios3/nagios.cfg && sudo /etc/init.d/nagios3 restart
  • Inviare una notifica custom

Riferimenti


Troubleshooting

sudoedit /etc/nagios3/nagios.cfg 

debug_level=2048

sudo invoke-rc.d nagios3 restart
tail -f /var/log/nagios3/nagios.debug