# Email me if BGP session status in NOT established

**URL:** <https://forum.mikrotik.com/t/email-me-if-bgp-session-status-in-not-established/58669>\
**Category:** Scripting\
**Created:** [August 7, 2012, 10:49am UTC](https://forum.mikrotik.com/t/email-me-if-bgp-session-status-in-not-established/58669 "2012-08-07T10:49:45Z")\
**Posts on this page:** 12\
**Page:** 2

<div class="post-metadata">

**Author:** ![dsfak](https://forum.mikrotik.com/letter_avatar/dsfak/32/6_449c533f586939b6e5f246632a46421f.png) [@dsfak](https://forum.mikrotik.com/u/dsfak)\
**Post date:** [March 28, 2023, 3:12pm UTC](https://forum.mikrotik.com/t/email-me-if-bgp-session-status-in-not-established/58669/21 "2023-03-28T15:12:24Z")

</div>

Bump !

---

<div class="post-metadata">

**Author:** ![nichky](https://forum.mikrotik.com/user_avatar/forum.mikrotik.com/nichky/32/1516_2.png) [@nichky](https://forum.mikrotik.com/u/nichky)\
**Post date:** [March 29, 2023, 1:50am UTC](https://forum.mikrotik.com/t/email-me-if-bgp-session-status-in-not-established/58669/22 "2023-03-29T01:50:44Z")

</div>

has this script been tested on v7?

---

<div class="post-metadata">

**Author:** ![Cha0s](https://forum.mikrotik.com/user_avatar/forum.mikrotik.com/cha0s/32/129_2.png) [@Cha0s](https://forum.mikrotik.com/u/Cha0s)\
**Post date:** [March 29, 2023, 7:27am UTC](https://forum.mikrotik.com/t/email-me-if-bgp-session-status-in-not-established/58669/23 "2023-03-29T07:27:56Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![chubbs596](https://forum.mikrotik.com/letter_avatar/chubbs596/32/6_449c533f586939b6e5f246632a46421f.png) [@chubbs596](https://forum.mikrotik.com/u/chubbs596)\
**Post date:** [May 29, 2023, 1:56pm UTC](https://forum.mikrotik.com/t/email-me-if-bgp-session-status-in-not-established/58669/24 "2023-05-29T13:56:02Z")

</div>

> [@](#):
>
> 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?

---

<div class="post-metadata">

**Author:** ![Cha0s](https://forum.mikrotik.com/user_avatar/forum.mikrotik.com/cha0s/32/129_2.png) [@Cha0s](https://forum.mikrotik.com/u/Cha0s)\
**Post date:** [March 2, 2024, 12:40pm UTC](https://forum.mikrotik.com/t/email-me-if-bgp-session-status-in-not-established/58669/25 "2024-03-02T12:40:53Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![ditud](https://forum.mikrotik.com/letter_avatar/ditud/32/6_449c533f586939b6e5f246632a46421f.png) [@ditud](https://forum.mikrotik.com/u/ditud)\
**Post date:** [March 2, 2024, 4:27pm UTC](https://forum.mikrotik.com/t/email-me-if-bgp-session-status-in-not-established/58669/26 "2024-03-02T16:27:33Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![Cha0s](https://forum.mikrotik.com/user_avatar/forum.mikrotik.com/cha0s/32/129_2.png) [@Cha0s](https://forum.mikrotik.com/u/Cha0s)\
**Post date:** [March 2, 2024, 5:19pm UTC](https://forum.mikrotik.com/t/email-me-if-bgp-session-status-in-not-established/58669/27 "2024-03-02T17:19:24Z")

</div>

> [@](#):
>
> 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).

```plaintext
/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:**

```plaintext
###################################################################
# BGP PEERS STATUS MAIL ALERT SCRIPT (for RouterOS v6 only) #
# Original Author: Cha0s, circa 2015, with improvements by JB172 #
# Info: http://forum.mikrotik.com/t/email-me-if-bgp-session-status-in-not-established/58669/15 #
###################################################################
# 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===============" )
}

```

---

<div class="post-metadata">

**Author:** ![Cha0s](https://forum.mikrotik.com/user_avatar/forum.mikrotik.com/cha0s/32/129_2.png) [@Cha0s](https://forum.mikrotik.com/u/Cha0s)\
**Post date:** [March 2, 2024, 11:07pm UTC](https://forum.mikrotik.com/t/email-me-if-bgp-session-status-in-not-established/58669/28 "2024-03-02T23:07:35Z")

</div>

> [@](#):
>
> 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:**

```plaintext
###################################################################
# BGP PEERS STATUS MAIL ALERT SCRIPT (for RouterOS v7 only) #
# Original Author: Cha0s, circa 2015, with improvements by JB172 #
# Info: http://forum.mikrotik.com/t/email-me-if-bgp-session-status-in-not-established/58669/15 #
###################################################################

# 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===============" )
}

```

---

<div class="post-metadata">

**Author:** ![ditud](https://forum.mikrotik.com/letter_avatar/ditud/32/6_449c533f586939b6e5f246632a46421f.png) [@ditud](https://forum.mikrotik.com/u/ditud)\
**Post date:** [March 3, 2024, 9:13pm UTC](https://forum.mikrotik.com/t/email-me-if-bgp-session-status-in-not-established/58669/29 "2024-03-03T21:13:49Z")

</div>

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.
> 
> ```plaintext
> ###################################################################
> # BGP PEERS STATUS MAIL ALERT SCRIPT (for RouterOS v6 only) #
> # Original Author: Cha0s, circa 2015, with improvements by JB172 #
> # Info: http://forum.mikrotik.com/t/email-me-if-bgp-session-status-in-not-established/58669/15 #
> ###################################################################
> 
> ```

```auto
[/quote]
```

---

<div class="post-metadata">

**Author:** ![Cha0s](https://forum.mikrotik.com/user_avatar/forum.mikrotik.com/cha0s/32/129_2.png) [@Cha0s](https://forum.mikrotik.com/u/Cha0s)\
**Post date:** [March 3, 2024, 9:23pm UTC](https://forum.mikrotik.com/t/email-me-if-bgp-session-status-in-not-established/58669/30 "2024-03-03T21:23:48Z")

</div>

There was a syntax error.  
I’ve edited my post with the correct syntax. Please try again, it should work now.

---

<div class="post-metadata">

**Author:** ![ditud](https://forum.mikrotik.com/letter_avatar/ditud/32/6_449c533f586939b6e5f246632a46421f.png) [@ditud](https://forum.mikrotik.com/u/ditud)\
**Post date:** [March 5, 2024, 7:39am UTC](https://forum.mikrotik.com/t/email-me-if-bgp-session-status-in-not-established/58669/31 "2024-03-05T07:39:41Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![baragoon](https://forum.mikrotik.com/user_avatar/forum.mikrotik.com/baragoon/32/61605_2.png) [@baragoon](https://forum.mikrotik.com/u/baragoon)\
**Post date:** [March 5, 2024, 7:53am UTC](https://forum.mikrotik.com/t/email-me-if-bgp-session-status-in-not-established/58669/32 "2024-03-05T07:53:56Z")

</div>

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

[Previous page](https://forum.mikrotik.com/t/email-me-if-bgp-session-status-in-not-established/58669.md?page=1)
