Please forgive me if I have re-invented the wheel! But I have been looking for a Script that would monitor an IPSec tunnel and if it couldn’t reach the endpoint it would force the tunnel to restart, unfortunately I couldn’t find any script to do quite what i wanted, so I borrowed some peoples code from other scripts and had a go myself, the below is what I have come up with constructive comments are welcome but please remember that this is the first script I have ever written.
{
:log info “IPSec Watchdog Started”
The host you want to ping######
:local HOST “Type IP Here”
Location of host########
:local LOCATION “Name of location”
Interface to Remote Network#######
:local GW “interface with route to host”
Ping Time out Increase or decrease as Required
:local TIMEOUT “100ms”
How Many try’s
:local COUNT “10”
If less than 8 successful reply’s Restart IPSec#####
:local LESSTHAN “8”
##################################DONT EDIT BELOW###################################
:log info “Looking for $HOST at $LOCATION”
:log info “Route to IPSec endpoint in $LOCATION is via $GW”
:if ([/ping interface=$GW $HOST interval=$TIMEOUT count=$COUNT]<$LESSTHAN)
do={log error “$HOST at $LOCATION is unreachable Tunnel to $LOCATION is Down Forcing IPSec Restart”; /ip ipsec installed-sa flush}
else {:log warning “IPSec Tunnel to $LOCATION is OK Nothing to do”}
}
Using NordVPN on my Mikrotik router I came across with the same issue - when IPsec tunnel occasionally stucks.
Thanks to all who posted scripts in this thread, it was a good start which helped me to begin learning Mikrotik scripting language.
I added a little dynamics thing in my version of script, perhaps it will help to somebody as well:
#get IPsec src-address from IPsec policies:
:local IPsecSrcIP [/ip/ipsec/policy get [find where tunnel=yes] src-address]
#remove netmask:
:set IPsecSrcIP [:pick $IPsecSrcIP 0 [:find $IPsecSrcIP "/"]]
#:log info "IPSec tunnel check: Pinging 8.8.8.8 via $IPsecSrcIP"
if ([/ping 8.8.8.8 src-address=$IPsecSrcIP count=5]=0) do={
:log warning "IPSec tunnel check: Ping to 8.8.8.8 via $IPsecSrcIP failed. VPN is down, Killing konnections"
:local enabledpeers [/ip/ipsec/peer find where disabled=no]
:foreach k,v in=$enabledpeers do={
/ip/ipsec/peer disable $v
}
/ip/ipsec/active-peers/ kill-connections
/ip/ipsec/installed-sa/ flush
:foreach k,v in=$enabledpeers do={
/ip/ipsec/peer enable $v
}
} else={
#:log info "IPSec tunnel check: Ping OK"
}
First of all, fix all error you have introduced on the script, like the space here: “tunnel =yes”, second, the script is v7 and you try to use it on v6.