Using a script to change IPSEC VPN Peer

I’ve been doing some digging lately around some unstable VPN connectivity using IKEv2 to Nord.

I have the following script, which is working well.

:local IPWatchServer 8.8.8.8
:local OutInterface bridge
:if ([/ping interface=$OutInterface $IPWatchServer count=5]<3) do={
  /ip ipsec installed-sa flush 
  :log info "IPSEC tunnel is down: Flushing Installed SA !!!"
} else={
#  :log info "IPSEC tunnel is OK !"
}

What I’ve noticed is that some peers/servers are more troublesome than others, and I find myself changing the server from time to time. I’d like to build this into the script to automatically update the peer. In my mind it would work along the lines of…

  • When the ping fails and triggers a flush, also increment a counter
  • When counter gets to say, 10..
    → Edit the existing Peer to change the address to a new server (I can’t have more than 1 peer called ‘NordVPN’)
  • Ideally, the new server will be chosen at Random from a list that I upload

My questions:

Can I add a counter in the script that will increment when the ping if statement is true? And where will that live? Just in memory? Or would I need to write an updated value to a file and read that each time? The script runs often, every 30 seconds, so I was wondering about instability/lag here

Can I refer to a list when setting the new peer? Something like…

/ipsec peer set address=<line at random from list> 0

Bonus: Remove ‘faulty’ peer from list

Alternatively, if not based on a count, then a time, say 7 days - I am again curious how that is counted/tracked and any implications on memory

I’ve seen examples reading lists of firewall rules, and I also found this thread http://forum.mikrotik.com/t/read-and-write-a-file-txt/47419/6

It looks like I could add the servers in a file like this:

:local filename "test.txt";

But what is not clear is, how i’d read this and extract a random line to use in the set command, so any guidance is appreciated.

Thanks!

I’m trying to figure out the very same thing and I’m also stuck. Can someone help please? Thank you!

I’m also looking for a way to switch to different peers in case the current peer isn’t ok.

For now, maybe I’ll add all peers that I want to connect to in:

  1. Peers (disabled)
  2. Identities

Something like NordVPN-RO-10/11/12/etc

I don’t know if there is a way to monitor the ipsec tunnel itself (ping / etc), but maybe via uptime - if current peer uptime is > 6h:

  1. Disconnect it
  2. Disable it
  3. Choose from the added peers based on random number and enable it - it should connect automatically..