17 มิถุนายน 2567

Mikrotik script monitor wireguard connection and reconnect with new listen port

wireguard name : wg1
port range : 13232 - 13239

/system script
add dont-require-permissions=no name=checkWireguard owner=admin source=":local wgName wg1;\r\
    \n:local newPort [:rndstr length=1 from=\"23456789\"];\r\
    \n:local newPort (\"1323\".\$newPort);\r\
    \n\r\
    \n:if ([/interface wireguard get [find name=\$wgName] running] = true) do={\r\
    \n\r\
    \n  :local pingResult [/ping count=1 10.10.10.1];\r\
    \n\r\
    \n  :if (\$pingResult = 0) do={\r\
    \n\r\
    \n    :log warning \"\$wgName connection lost. Changing listen port...\";\r\
    \n\r\
    \n    /interface wireguard set [find name=\$wgName] disabled=yes\r\
    \n    /interface wireguard set [find name=\$wgName] listen-port=\$newPort;\r\
    \n    /interface wireguard set [find name=\$wgName] disabled=no\r\
    \n\r\
    \n    :local currentPort [/interface wireguard get [find name=\$wgName] listen-port];\r\
    \n    :log warning \"WireGuard \$wgName listen port changed to \$currentPort\";\r\
    \n\r\
    \n  }\r\
    \n  \r\
    \n}"

/system scheduler
add interval=1m name=checkWireguard on-event=checkWireguard start-time=startup