Invio di notifiche Nagios con Telegram

From RVM Wiki
Jump to navigation Jump to search

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