[ Mikrotik ] Script para comprobar los peers BGP

Ante todo, decir que este script para comprobar el estado de los peers BGP en Mikrotik no es mío. Pero me parece muy interesante y por eso he decidido publicarlo. Lo encontré en el foro de Mikrotik y fue creado por el usuario cha0s.

El script lo que hace es recorrer los peers que tengamos creados en el Mikrotik, y buscar el estado. Si está established o disabled, el script los omite porque ya están conectados o hemos sido nosotros lo que lo hemos desactivado a posta.

Como siempre indicar que hay que modificar la dirección de correo electrónico a la que envía la notificación.

Mi recomendación es configurar en el scheduler para que el Mikrotik lo ejecute periodicamente según nosotros queramos, de esta manera siempre estaremos informados del estado de los peers que tenemos configurados en nuestro Mikrotik.

Aquí tenéis el código:

 

# EDIT HERE
:local arrEmails [:toarray "email@example.net,email2@example.net"];
:local debug true
# EDIT END

# Define Variables
:global arrBgpState;
:global gotKey false;
:local hostNameX ([/system identity get name]);
:local statusX;
:local peerX;
:local peerXarrEl;
:local mailToX;
:local mailSubjectX;
:local mailBodyX;
:local peerStatusX;
:local arrBgpPeers [:toarray ""];
:local peername "";
:local peerTotal "";

if ($debug = true) do={
   :log info ("=============BGP PEER STATUS DETECTION STARTED=============" )
}

# Initialize global array - kinda lame way to do it :P
:if ( [:len $arrBgpState] =0 ) do={
   :set $arrBgpState {"false"="false"}
}

# Fill arrBgpPeers array with peers name
:foreach i in=[/routing bgp peer find] do={
:set peername [/routing bgp peer get $i name];
:set peerTotal ($peerTotal . "," .$peername);
}
:set arrBgpPeers [:toarray $peerTotal];

# Loop through the peers array
:local arrPos
:for arrPos from=0 to=([:len $arrBgpPeers]-1) do={

   # Set peerX to current peer name for this iteration
   :set peerX [:pick $arrBgpPeers $arrPos];

   # Check if peer is enabled and proceed
   :if ([/routing bgp peer get [find name=$peerX] disabled ] != true) do={
      
      # Get Peer Status
      :set peerStatusX [/routing bgp peer get [find name="$peerX"] state]

      # Find peer key in global array
      :foreach k,v in=$arrBgpState do={
         if ($k != "false") do={
            :if ($gotKey = false) do={
               :if ($k = $peerX) do={
                  :set gotKey true
               }
            }
         }
      }
      
      # Initialize arrBgpState array element with peerX name if it doesn't already exist
      :if ($gotKey = false) do={
         :set ($arrBgpState->"$peerX") "up"
      }
      
      # Reset this for the next iteration
      :set gotKey false   
      
      # Previous run peer status
      :set statusX ($arrBgpState->"$peerX")
      
      # Prepare Email body
      :set mailBodyX ("Router Hostname: " . $hostNameX . "\nBGP Peer Status: " . $peerStatusX . "\nBGP Peer Name: " . $peerX . "\n");
      
      # Check if BGP Peer is not established
      :if ($peerStatusX != "established") do={
        
          # Check if this is the first time the peer is doen
          :if ( $statusX  = "up" ) do={
            
            # Set value to 'down' to peer global var key
            :set ($arrBgpState->$peerX) "down"

            # Informational Log
            if ($debug = true) do={
               :log error ("BGP Peer ". $peerX ." state is " . $peerStatusX . ". Sending email alerts!" )
            }

            # Prepare Email subject
            :set mailSubjectX ("BGP Peer ". $peerX ." on ". $hostNameX . " is NOT established!");
            
            # Loop over emails array to send emails to all recipients in array
            :local arrPos2
            :for arrPos2 from=0 to=([:len $arrEmails]-1) do={
               # Set mailToX to recipient for this iteration
               :set mailToX [:pick $arrEmails $arrPos2]
               
               # Informational Log
               :log error ("BGP Peer " . $peerX . " status is " .$peerStatusX. "! Sending Email alert to " . $mailToX . "." )
                     
               # Send Email
               /tool e-mail send to=$mailToX subject=$mailSubjectX body=$mailBodyX;
            }        

         } else={
            # Peer down. Already sent notification so do nothing.
            if ($debug = true) do={
               :log info ("BGP Peer ". $peerX ." is already down. Ignoring!")
            }
         }

      } else={
         
         # Check if peer just came back up and send informational email
         if ($statusX = "down") do={
            
            # Prepare Email subject
            :set mailSubjectX ("BGP Peer ". $peerX ." on ". $hostNameX . " has recovered!");
                     
            # Loop over emails array to send emails to all recipients in array
            :local arrPos2
            :for arrPos2 from=0 to=([:len $arrEmails]-1) do={
               # Set mailToX to recepient for this iteration
               :set mailToX [:pick $arrEmails $arrPos2]
               
               # Informational Log
               :log warning ("BGP Peer " . $peerX . " status has recovered! Sending informational Email to " . $mailToX . "." )
                     
               # Send Email
               /tool e-mail send to=$mailToX subject=$mailSubjectX body=$mailBodyX;
            }            
            
         }
         
         if ($debug = true) do={
            :log info ("BGP Peer " . $peerX . " is up. Nothing to do!")
         }
         
         # Set peer status to up
         :set ($arrBgpState->$peerX) "up"
      }      
      
   } else={
      if ($debug = true) do={
         :log warning ("BGP Peer " . $peerX . " is disabled. Ignoring!")
      }
   }   
      
}

if ($debug = true) do={
   :log info ("=============BGP PEER STATUS DETECTION ENDED===============" )
}

Podéis encontrar otros scripts para Mikrotik que he creado o he considerado importates compartir en esta misma web.

Mikrotik

Mikrotik

Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *

Human Verification: In order to verify that you are a human and not a spam bot, please enter the answer into the following box below based on the instructions contained in the graphic.


This blog is kept spam free by WP-SpamFree.