Community discussions

MikroTik App
 
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: 7038
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: 7038
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: 7038
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: 2509
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: 2509
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: 2509
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 Guru
Forum Guru
Posts: 1135
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.
###################################################################
# BGP PEERS STATUS MAIL ALERT SCRIPT (for RouterOS v6 only)       #
# Original Author: Cha0s, circa 2015, with improvements by JB172  #
# Info: https://forum.mikrotik.com/viewtopic.php?p=494204#p494204 #
###################################################################
# 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 :)
Last edited by Cha0s on Sun Mar 03, 2024 1:14 am, edited 1 time in total.
 
plisken
Forum Guru
Forum Guru
Posts: 2509
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 Guru
Forum Guru
Posts: 1135
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 :)
###################################################################
# BGP PEERS STATUS MAIL ALERT SCRIPT (for RouterOS v6 only)       #
# Original Author: Cha0s, circa 2015, with improvements by JB172  #
# Info: https://forum.mikrotik.com/viewtopic.php?p=494204#p494204 #
###################################################################
# 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===============" )
}
Last edited by Cha0s on Sun Mar 03, 2024 1:14 am, edited 1 time in total.
 
plisken
Forum Guru
Forum Guru
Posts: 2509
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!
 
ajayyadav941
just joined
Posts: 2
Joined: Thu Nov 15, 2018 7:19 pm
Location: india

Re: Email me if BGP session status in NOT established

Thu Nov 15, 2018 7:48 pm

Hello

Can any one give me all step by step configuration.that how to get Email when BGP session goes down
 
dsfak
just joined
Posts: 2
Joined: Thu Jul 12, 2012 10:40 pm

Re: Email me if BGP session status in NOT established

Fri Dec 09, 2022 10:43 am

Hello guys,

@Cha0s : Your script is working very good ! Do you have any update of it for version 7 ? Because it's not working and I'm trying to convert it to v7 but with no success... !
 
dsfak
just joined
Posts: 2
Joined: Thu Jul 12, 2012 10:40 pm

Re: Email me if BGP session status in NOT established

Tue Mar 28, 2023 6:12 pm

Bump !
 
User avatar
nichky
Forum Guru
Forum Guru
Posts: 1275
Joined: Tue Jun 23, 2015 2:35 pm

Re: Email me if BGP session status in NOT established

Wed Mar 29, 2023 4:50 am

has this script been tested on v7?
 
User avatar
Cha0s
Forum Guru
Forum Guru
Posts: 1135
Joined: Tue Oct 11, 2005 4:53 pm

Re: Email me if BGP session status in NOT established

Wed Mar 29, 2023 10:27 am

Hello,

I don't use v7 yet since it's far from production ready (especially when it comes to BGP/BFD), so I haven't tested the script on it.
 
chubbs596
Frequent Visitor
Frequent Visitor
Posts: 90
Joined: Fri Dec 06, 2013 6:07 pm

Re: Email me if BGP session status in NOT established

Mon May 29, 2023 4:56 pm

Hello,

I don't use v7 yet since it's far from production ready (especially when it comes to BGP/BFD), so I haven't tested the script on it.
Hi,
Now that BFD has been added in V7.10beta8, will you possible start looking at converting this script for V7?
 
User avatar
Cha0s
Forum Guru
Forum Guru
Posts: 1135
Joined: Tue Oct 11, 2005 4:53 pm

Re: Email me if BGP session status in NOT established

Sat Mar 02, 2024 2:40 pm

I don't think that my approach will work on v7 since the sessions are radically different from v6.
It will probably need a complete rewrite to make it work on v7. I am not promising anything.
 
ditud
just joined
Posts: 4
Joined: Wed Jan 27, 2021 10:09 am

Re: Email me if BGP session status in NOT established

Sat Mar 02, 2024 6:27 pm

I'm using this script and I'm happy with job it's doing.

I have a BGP session that turn down from time to time and I have to disable it manualy and then enable to establish it again. I wonder how to do a small script upgrade so it would do that automaticly?

I would be very greatful for an example.
 
User avatar
Cha0s
Forum Guru
Forum Guru
Posts: 1135
Joined: Tue Oct 11, 2005 4:53 pm

Re: Email me if BGP session status in NOT established

Sat Mar 02, 2024 7:19 pm

I'm using this script and I'm happy with job it's doing.

I have a BGP session that turn down from time to time and I have to disable it manualy and then enable to establish it again. I wonder how to do a small script upgrade so it would do that automaticly?

I would be very greatful for an example.
You mean in v6, right? The peer gets stuck in 'opensent' status?
I haven't seen this behavior in v7.

In v6 you can use the following script in a scheduler every 1 minute (or however fast you want).
/routing bgp peer {
   :foreach peer in [find state="opensent"] do={
      :log warning "Restart stuck BGP Peer: $([get $peer name])"
      disable $peer
      enable $peer
   }
}
I've integrated the above script into my mail alert script but I haven't tested it.

BGP PEERS STATUS MAIL ALERT SCRIPT for RouterOS v6:
###################################################################
# BGP PEERS STATUS MAIL ALERT SCRIPT (for RouterOS v6 only)       #
# Original Author: Cha0s, circa 2015, with improvements by JB172  #
# Info: https://forum.mikrotik.com/viewtopic.php?p=494204#p494204 #
###################################################################
# 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 peer is stuck in opensent status an disable/enable to get it unstuck
         if ($peerStatusX = "opensent") do={
            :log warning "Restart stuck BGP Peer: $peerX"
            /routing bgp peer disable $peerX
            /routing bgp peer enable $peerX
         }         
        
         # 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===============" )
}
Last edited by Cha0s on Sun Mar 03, 2024 11:24 pm, edited 3 times in total.
 
User avatar
Cha0s
Forum Guru
Forum Guru
Posts: 1135
Joined: Tue Oct 11, 2005 4:53 pm

Re: Email me if BGP session status in NOT established

Sun Mar 03, 2024 1:07 am

I don't think that my approach will work on v7 since the sessions are radically different from v6.
It will probably need a complete rewrite to make it work on v7. I am not promising anything.
It turns out it was easier than I thought.

I haven't tested the script extensively, so use at your own risk.

BGP PEERS STATUS MAIL ALERT SCRIPT for RouterOS v7:
###################################################################
# BGP PEERS STATUS MAIL ALERT SCRIPT (for RouterOS v7 only)       #
# Original Author: Cha0s, circa 2015, with improvements by JB172  #
# Info: https://forum.mikrotik.com/viewtopic.php?p=494204#p494204 #
###################################################################

# EDIT HERE
:local arrEmails [:toarray "email@example.net,email2@example.net"];
:local debug false
# 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 "";
:local notifStatus "";

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 session find] do={
:set peername [/routing bgp session 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];
      
   # Get Peer Status
   :set peerStatusX [/routing bgp session get [find name="$peerX"] established]

   if ($peerStatusX = true) do={
      :set notifStatus ("up");
   } else={
      :set notifStatus ("down");
   }

   # 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: " . $notifStatus . "\nBGP Peer Name: " . $peerX . "\n");
   
   # Check if BGP Peer is not established
   :if ($peerStatusX != true) 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 " . $notifStatus . ". 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 " .$notifStatus. "! 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"
   }           

}

if ($debug = true) do={
   :log info ("=============BGP PEER STATUS DETECTION ENDED===============" )
}
 
ditud
just joined
Posts: 4
Joined: Wed Jan 27, 2021 10:09 am

Re: Email me if BGP session status in NOT established

Sun Mar 03, 2024 11:13 pm

I run script in this form but nothing happend. I also put lines below in my aold script:

# Check if peer is stuck in opensent status an disable/enable to get it unstuck
if ($peerStatusX = "opensent") do={
:log warning "Restart stuck BGP Peer: " . $peerX
/routing bgp peer disable $peerX
/routing bgp peer enable $peerX
}


but after run, nothing happend. Log on mikrotik shows no new lines.

It's routeros v6 and exactly this is opensent state situation.
I've integrated the above script into my mail alert script but I haven't tested it.
###################################################################
# BGP PEERS STATUS MAIL ALERT SCRIPT (for RouterOS v6 only)       #
# Original Author: Cha0s, circa 2015, with improvements by JB172  #
# Info: https://forum.mikrotik.com/viewtopic.php?p=494204#p494204 #
###################################################################
[/quote]
 
User avatar
Cha0s
Forum Guru
Forum Guru
Posts: 1135
Joined: Tue Oct 11, 2005 4:53 pm

Re: Email me if BGP session status in NOT established

Sun Mar 03, 2024 11:23 pm

There was a syntax error.
I've edited my post with the correct syntax. Please try again, it should work now.
 
ditud
just joined
Posts: 4
Joined: Wed Jan 27, 2021 10:09 am

Re: Email me if BGP session status in NOT established

Tue Mar 05, 2024 9:39 am

Three times this night one session went down and three times it established again after next script run. It seems that it works.
There was a syntax error.
I've edited my post with the correct syntax. Please try again, it should work now.
 
User avatar
baragoon
Member Candidate
Member Candidate
Posts: 294
Joined: Thu Jan 05, 2017 10:38 am
Location: Kyiv, UA
Contact:

Re: Email me if BGP session status in NOT established

Tue Mar 05, 2024 9:53 am

Thank you, very useful!
But I think, that peers must be declared from /routing/bgp/connection and then compared with /routing/bgp/session for v7

Who is online

Users browsing this forum: baragoon, GoogleOther [Bot] and 16 guests