Community discussions

 
FearlessRabbitt
just joined
Topic Author
Posts: 10
Joined: Tue Aug 07, 2012 1:33 pm

Email me if BGP session status in NOT established

Tue Aug 07, 2012 1:49 pm

Hi guys,

I`d like to create a script which would email me if BGP session is NOT established. This is the only BGP state I`m interested in. I currently have basic Netwatch configured to email me if ISP gateway is not reachable, but this is not enough.

Could you point me in right direction on how to configure this? Please have in back of your minds my programming/scripting knowledge is not existent :)

Thank you
 
FearlessRabbitt
just joined
Topic Author
Posts: 10
Joined: Tue Aug 07, 2012 1:33 pm

Re: Email me if BGP session status in NOT established

Wed Aug 08, 2012 1:07 pm

What I know so far:

Command I need is /routing bgp peer print status. The output is something like this:

name="tcom" instance=default remote-address=213.149.123.81 remote-as=29453 tcp-md5-key="" nexthop-choice=default
multihop=no route-reflect=no hold-time=3m ttl=default in-filter="" out-filter=t-com-out address-families=ip
default-originate=never remove-private-as=no as-override=no passive=no use-bfd=no remote-id=195.140.164.68
local-address=213.149.123.82 uptime=9w6d7h2m41s prefix-count=1 updates-sent=12 updates-received=1 withdrawn-sent=9
withdrawn-received=0 remote-hold-time=3m used-hold-time=3m used-keepalive-time=1m refresh-capability=yes
as4-capability=yes state=established


Now how the heck could I create a script which would run this command every 5 minutes and send me an email if state is not established :(
 
User avatar
mrz
MikroTik Support
MikroTik Support
Posts: 5549
Joined: Wed Feb 07, 2007 12:45 pm
Location: Latvia
Contact:

Re: Email me if BGP session status in NOT established

Wed Aug 08, 2012 2:15 pm

add scheduled script
:if ([/routing bgp peer get [find name="xxx"] state] != "established") do={ .. send email here...}
 
FearlessRabbitt
just joined
Topic Author
Posts: 10
Joined: Tue Aug 07, 2012 1:33 pm

Re: Email me if BGP session status in NOT established

Wed Aug 08, 2012 2:16 pm

Trying to edit some similar script I found on the forums, wonder if I`m close?

:global bgpest;
:global bgpest "established";
:local bgpstate [/routing bgp peer get [find where state=established]];

:if ($bgpest != $bgpstate) do={
    /tool e-mail send from=mikrotikDV@portomontenegro.com server=91.220.187.8
to=mvujkovic@portomontenegro.com subject="bgp script test"
}


Becoming desperate :(
 
FearlessRabbitt
just joined
Topic Author
Posts: 10
Joined: Tue Aug 07, 2012 1:33 pm

Re: Email me if BGP session status in NOT established

Wed Aug 08, 2012 2:38 pm

add scheduled script
:if ([/routing bgp peer get [find name="xxx"] state] != "established") do={ .. send email here...}
Thank you for your reply! Highly appreciated!
In System / Script menu I created a new script consisted of:

:if ([/routing bgp peer get [find name="mina"] state] != "established") do={/tool e-mail send from=mikrotikDV@portomontenegro.com server=91.220.187.8
to=mvujkovic@portomontenegro.com subject="bgp script test"}


Then I disable "mina" peer, run the script manually, and wait for that test email to arrive. Nothing happens, I must be doing something wrong? :oops:
 
User avatar
mrz
MikroTik Support
MikroTik Support
Posts: 5549
Joined: Wed Feb 07, 2007 12:45 pm
Location: Latvia
Contact:

Re: Email me if BGP session status in NOT established

Wed Aug 08, 2012 2:46 pm

Script works for me fine. If you do not receive email then check your email settings. It may require username and password or starttls option.
 
FearlessRabbitt
just joined
Topic Author
Posts: 10
Joined: Tue Aug 07, 2012 1:33 pm

Re: Email me if BGP session status in NOT established

Wed Aug 08, 2012 3:14 pm

This might be a stupid question: I just copy and paste the code into the Script menu (attached)?
You do not have the required permissions to view the files attached to this post.
 
FearlessRabbitt
just joined
Topic Author
Posts: 10
Joined: Tue Aug 07, 2012 1:33 pm

Re: Email me if BGP session status in NOT established

Wed Aug 08, 2012 4:43 pm

Tried manually entering the code directly into the command line, and got the syntax error at "=". Second run was without "=", and received no such item message. Any clue? :-|
You do not have the required permissions to view the files attached to this post.
 
FearlessRabbitt
just joined
Topic Author
Posts: 10
Joined: Tue Aug 07, 2012 1:33 pm

Re: Email me if BGP session status in NOT established

Wed Aug 08, 2012 6:46 pm

And after whole day of playing around, I got the winner! Here it is if someone else needs it:

:if ([/routing bgp peer get [find name=mina] state] != "established") do={ -- send email --}

Basically I was using find name="mina", and it wouldnt work with quotation signs :? Who knew :D
 
directlogic
newbie
Posts: 40
Joined: Wed Aug 19, 2009 12:29 pm

Re: Email me if BGP session status in NOT established

Thu May 23, 2013 4:54 pm

Dear All,

This script test BGP sessions and if not established if send mail, but If BGP was down more then horn then it send so many mails. how to prevent this type of situation and script only send mail once.

Thanks,
 
User avatar
mrz
MikroTik Support
MikroTik Support
Posts: 5549
Joined: Wed Feb 07, 2007 12:45 pm
Location: Latvia
Contact:

Re: Email me if BGP session status in NOT established

Thu May 23, 2013 5:16 pm

You need additional check.
If state is not established set global variable that peer is marked as down. Next time when script runs check and send email only if previously was established.
 
plisken
Forum Guru
Forum Guru
Posts: 2259
Joined: Sun May 15, 2011 12:24 am
Location: Belgium
Contact:

Re: Email me if BGP session status in NOT established

Sat May 03, 2014 2:34 pm

Can you shown the complete working script please so i can copy and paste this script.
I have try many times but now success
Thanks
 
plisken
Forum Guru
Forum Guru
Posts: 2259
Joined: Sun May 15, 2011 12:24 am
Location: Belgium
Contact:

Re: Email me if BGP session status in NOT established

Fri May 09, 2014 3:40 pm

What script to disable ether2 if bgp peer is established?

add scheduled script
:if ([/routing bgp peer get [find name="xxx"] state] != "established") do={ .. send email here...}
 
plisken
Forum Guru
Forum Guru
Posts: 2259
Joined: Sun May 15, 2011 12:24 am
Location: Belgium
Contact:

Re: Email me if BGP session status in NOT established

Sat May 10, 2014 1:34 pm

Can you write the full script with email commands etc please
i use pop3 server port 25

Script works for me fine. If you do not receive email then check your email settings. It may require username and password or starttls option.
 
User avatar
Cha0s
Forum Veteran
Forum Veteran
Posts: 767
Joined: Tue Oct 11, 2005 4:53 pm

Re: Email me if BGP session status in NOT established

Sat Aug 08, 2015 4:36 am

I was looking for the same script to get alerts when any bgp peer goes down.

I didn't find anything complete so I wrote a script based on what was suggested on this thread.
It's a single script that supports multiple peers and multiple emails for getting alerts.
It assumes that /tools email is properly configured on the router.

The script will periodically (you run it with scheduler - I run it every 10 seconds with no issues so far) check all configured BGP peers.
-If a peer is disabled it will ignore it.
-If a peer is with state 'established' it will ignore it.
-If a peer has any other state than 'established' it will send an informational email to the configured email addresses and log this as an error (red) in the log window.
-If on the next run of the script the peer is still down it will remember it and will not send any emails again for that peer.
-If on the next run the peers that were down go back on state 'established' an informational email will be send to the configured email address and log this as a warning (blue) in the log window.

The script has been tested on v6.29 & v6.30.2. I don't know if it will work properly on older versions. (I know for sure that it doesn't work on 5.x and probably won't work on <=6.3)

Known issues:
If you do not define the bgp peers with their correct name, the script will not run successfully.


To use the script you only need to edit the two first arrays to add the names of your bgp peers and emails separated by commas.
There is also a debug option to enable more info on the log window. Set this to false to disable.

You don't need to edit anything else on the script. By simply running it it should not produce any output (if debug is off) when all peers are on state established.
# EDIT HERE
:local arrBgpPeers [:toarray "peer1,peer2,peer3"];
: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;

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"}
}

# 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===============" )
}
I am not very familiar with the RouterOS scripting language so there is definitely room for improvements on my code!
Feel free to edit it as you see fit :)
 
plisken
Forum Guru
Forum Guru
Posts: 2259
Joined: Sun May 15, 2011 12:24 am
Location: Belgium
Contact:

Re: Email me if BGP session status in NOT established

Sat Aug 08, 2015 10:10 am

Working like a charm
Very much appreciated
Thanks
 
User avatar
Cha0s
Forum Veteran
Forum Veteran
Posts: 767
Joined: Tue Oct 11, 2005 4:53 pm

Re: Email me if BGP session status in NOT established

Tue Sep 08, 2015 1:04 pm

Here's a slightly different version that will automatically find all configured BGP Peers and monitor them (instead of having to define each peer manually).

Thanks to JB172 for the patch :)
# 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===============" )
}
 
plisken
Forum Guru
Forum Guru
Posts: 2259
Joined: Sun May 15, 2011 12:24 am
Location: Belgium
Contact:

Re: Email me if BGP session status in NOT established

Tue Sep 08, 2015 7:13 pm

Working fine.
Great work!

Who is online

Users browsing this forum: No registered users and 2 guests