20 พฤศจิกายน 2566

Mikrotik script change wireguard listen port in case of unable to connect

Base on routerOS 7.12 
wireguard name : wg1
port range : 13232 - 13239

/system script
add dont-require-permissions=no name=checkWireguard owner=admin policy=ftp,reboot,read,write,policy,test,password,sniff,sensitive,romon 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