Community discussions

MikroTik App
 
User avatar
gyropilot
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 57
Joined: Sat Sep 10, 2016 10:49 pm
Location: SE Arizona USA

Script to Test WAN and Reset USB Power on Down?

Thu Feb 09, 2017 6:25 pm

I'm brand new to scripting and could use some help...

Can anyone point me to a simple script which essentially duplicates Netwatch (pinging an IP out on the WAN), but instead of executing an action after only one ping failure, have it test for multiple ping failures over a given period of time before executing an action?

Specifically, I'd like to execute a USB power-reset on an attached LTE cellular modem only after several ping failures in a row have occurred to reduce false positives which I think I'm getting using the Netwatch tool alone. After the WAN comes back up, I'd like the script to send me an email alert.

I've found a few improved Netwatch scripts in the wiki pages, but they're designed for failover and are just way too complicated for me to understand and therefore modify.

Thanks in advance,

John
 
User avatar
Larsa
Forum Guru
Forum Guru
Posts: 1059
Joined: Sat Aug 29, 2015 7:40 pm
Location: The North Pole, Santa's Workshop

Re: Script to Test WAN and Reset USB Power on Down?

Thu Feb 09, 2017 9:02 pm

I'm brand new to scripting and could use some help...
. . .
I've found a few improved Netwatch scripts in the wiki pages, but they're designed for failover and are just way too complicated for me to understand and therefore modify.
Well, http://wiki.mikrotik.com/wiki/Improved_Netwatch_II is the way to go although I'll admit the layout isn't pretty(!) and quite hard to understand! :D

Maybe this might be easier to read:
# Try to ping addr 5 times with an interval of 3 seconds
:local i 0; 

:do {
	:set i ($i + 1)
} while (($i < 5) && ([/ping 64.233.169.99 interval=3 count=1] = 0));

# If "$i" is set to 5 then default route is down and alter route prio to 3
:if ($i=5 && [/ip route get [find comment="Default Route"] distance] = 1) do = 
{
	:log info "Main Gateway down"; 
 	/ip route set [find comment="Default Route"] distance=3
}
 
User avatar
gyropilot
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 57
Joined: Sat Sep 10, 2016 10:49 pm
Location: SE Arizona USA

Re: Script to Test WAN and Reset USB Power on Down?

Thu Feb 09, 2017 11:14 pm

Thank you for the reply Larsa.
 
roanitonet
just joined
Posts: 7
Joined: Sun Feb 05, 2017 12:53 am
Location: Goias
Contact:

Re: Script to Test WAN and Reset USB Power on Down?

Sat Feb 11, 2017 3:11 am

I have a similar problem, but I need a script to see the IP that was received from the ppp-out connection (if the range starts with 100.0.0.0) it disables and enables the ppp-out interface again until it Ip valid.
Any script with this format
I'm brand new to scripting and could use some help...
. . .
I've found a few improved Netwatch scripts in the wiki pages, but they're designed for failover and are just way too complicated for me to understand and therefore modify.
Well, http://wiki.mikrotik.com/wiki/Improved_Netwatch_II is the way to go although I'll admit the layout isn't pretty(!) and quite hard to understand! :D

Maybe this might be easier to read:
# Try to ping addr 5 times with an interval of 3 seconds
:local i 0; 

:do {
	:set i ($i + 1)
} while (($i < 5) && ([/ping 64.233.169.99 interval=3 count=1] = 0));

# If "$i" is set to 5 then default route is down and alter route prio to 3
:if ($i=5 && [/ip route get [find comment="Default Route"] distance] = 1) do = 
{
	:log info "Main Gateway down"; 
 	/ip route set [find comment="Default Route"] distance=3
}
 
User avatar
SiB
Forum Guru
Forum Guru
Posts: 1888
Joined: Sun Jan 06, 2013 11:19 pm
Location: Poland

Re: Script to Test WAN and Reset USB Power on Down?

Mon Aug 26, 2019 1:56 am

This is not easy 3 line script. Some theory must be add.

Note: NetWatch when run UP-script or DOWN-script create a new job every times and owner of job is *sys user and previous/opposite job is not kill. Few changes of ISP and Netwatch run parallel jobs.
Multiple instances of up&down-script scripts duplication are the same job property, we can not select what job is up or down script.
They have many limitation as *sys user like global variable are real a local ones. We have not permission to remove a real one globals or create real one. Cannot create new script. We can create scheduler who can create scripts but all operations are with *sys user and are still limited.
Other limitation are: Netwatch not check few times until change state, Use only main route table, cannot use a specific src-address.
.
Very wrong situation. On some limitation we can use solution/workaround like:
* Use a separated "System Script" to identify scripts in script\jobs tab. We must use the "dont-require-permissions=yes" becuase NetWatch use *sys user but our system script use our logon user.
* Kill opposite one if still exist by e.g. /system script job remove [find script~"SomeOppositeScript"] but it must run as separate system script

Note: "Improved NetWatch II script" create a big infinite ":do loop" with additional pings who have latency and timeout, to many loops inside NetWatch itself. Additional NetWatch do his ping of state and we do pings from inside script's = dual ping from our router. Good example of use it is at "Enhanced NetWatch by manojlovicl"

Note: Main JOB is to do Re-Connect USB LTE connection
1) Turn off Power on USB port, not work at all RouterBoard with USB, list of devices are in https://wiki.mikrotik.com/wiki/Manual:U ... port_table like: RB750UP, RB751G-2HnD and RB751U-2HnD.
e.g. /system routerboard usb power-reset duration=3;
2) Just re-enable lte interface
e.g. /interface lte disable [find]; delay 3s; /interface lte enable [find];
3) at the end we must do a Reboot of MikroTik device.
e.g. /system reboot
other) of course are other like... modem can use PPP dial to re-connection or use a AT command is modem accept it bo change LTE Band, etc. etc.

My idea and solution.
Why anyone not thinking about NetWatch properties like Status && Since - both give us good feedback without additional own ping-loops.
We can create a simple scheduler from down-script to do a Main Job with limitation of *sys user to do our job in future like old "logic bomb" in virus terminology.
Simple solutions are the best, they say "Trust me, I'm an engineer" too :)
Check this out.

SiB way example:
1. Create NetWatch -> only it will do ping testing of target host and run up/down-script.
/tool netwatch add host=1.1.1.1 interval=10s timeout=500ms disabled=no comment=RePowerUSB
*) 2. Add UP-script -> Remove future action because ISP is up.
Do Nothing more.
/system scheduler remove [find where name~"SiBexRePowerUSBv"];
*) 3a. Add DOWN-script -> ReCreate future jobs before DeadLine came true in 5m or 7m and last hope do reboot in 15m.
# Add action to future via scheduler
/system scheduler remove [find where name~"SiBexRePowerUSBv"];
local now [/system clock get time];
/system scheduler add name=SiBexRePowerUSBv1 on-event={/system routerboard usb power-reset duration=3;} start-time=($now+5m );
/system scheduler add name=SiBexRePowerUSBv2 on-event={/interface lte disable [find]; delay 3s; /interface lte enable [find];} start-time=($now+7m );
/system scheduler add name=SiBexRePowerUSBv3 on-event={/system reboot;} start-time=($now+15m );
You see the idea now.
This is not work good when we have problems with ISP happen at 23:59:59 and the scheduler must be created next day, means when we must Crossing Midnight.

3b. Final Netwatch DOWN-script with function who resolve the Crossing Midnight problem is:
log error "start Netwatch DOWN-script...";

# ################ MAIN PROGRAM BELOW, NOT HERE ######################
# ################ DEFINE FUNCTION SOLVING Crossing Midnight ##############

/local SiBFixDateTime do={
#/local SiBTimeToChange "23:45:00";
/local SiBTimeToChange $2;
#/local SiBTimeDiffToAdd "60m2s"; # diff time < 24h
/local SiBTimeDiffToAdd $3; # diff time < 24h
#/local SiBDate "dec/31/2020"
/local SiBDate $1
/local SiBDateCorrected;

#log warning ("Source: ".$SiBDate." ".$SiBTimeToChange." + ".$SiBTimeDiffToAdd);
#put ("Source: ".$SiBDate." ".$SiBTimeToChange." + ".$SiBTimeDiffToAdd);

# Add diff time <=24h
/local SiBTimeAndDiffTime ($SiBTimeToChange + $SiBTimeDiffToAdd );
/if ([/len $SiBTimeAndDiffTime]=8) do={/set $SiBDateCorrected ($SiBDate." ".$SiBTimeAndDiffTime); };
/if ([/len $SiBTimeAndDiffTime]>8) do={
  /set $SiBTimeAndDiffTime ($SiBTimeAndDiffTime-1d);

  ## Add 24h to date, copy time if exist.
  set $SiBDateCorrected ($SiBDate." ".$SiBTimeAndDiffTime);

  # Days: 01-27
  local SiBDayToChange [/pick $SiBDateCorrected 4 6;];
  if ($SiBDayToChange<=27) do={
      set $SiBDayToChange ($SiBDayToChange+1);
      if ([/len $SiBDayToChange]=1) do={set $SiBDayToChange ("0".$SiBDayToChange)}
      set $SiBDateCorrected ( [/pick $SiBDateCorrected 0 4].$SiBDayToChange.[/pick $SiBDateCorrected 6 20] );
    } else={
      if ($SiBDayToChange!=31) do={

          # Days: 28..30; Main magic do internal scheduler.
          /system scheduler remove [find name=SiBTempScheduler2qw34er5v78bn90m];
          /system scheduler add name=SiBTempScheduler2qw34er5v78bn90m on-event={nothing } start-time=00:00:01 start-date=( [/pick $SiBDateCorrected 0 4].($SiBDayToChange+1).[/pick $SiBDateCorrected 6 11 ] );
          set $SiBDateCorrected ([system scheduler get [find name=SiBTempScheduler2qw34er5v78bn90m] start-date].[/pick $SiBDateCorrected 11 20 ]);
          /system scheduler remove [find name=SiBTempScheduler2qw34er5v78bn90m];
        } else={

          # Day 31 for Jan..Nov
          /local SiBMonths ("jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec");
          /local SiBMounthToChange [/pick $SiBDateCorrected 0 3];
          for x from=0 to=10 do={if ([/pick $SiBMonths $x]=$SiBMounthToChange) do={ set $SiBDateCorrected ([pick $SiBMonths ($x+1)]."/01".[/pick $SiBDateCorrected 6 20 ]) }}

          # Day 31 for Dec
          if ($SiBMounthToChange="dec") do={ set $SiBDateCorrected ("jan/01/".([/pick $SiBDateCorrected 7 11]+1).[/pick $SiBDateCorrected 11 20] )}
      };
    };
};

#log warning ("New date time: ".$SiBDateCorrected);
#put ("New date time: ".$SiBDateCorrected);
:return $SiBDateCorrected
};

# ################ MAIN PROGRAM ###########################

# Select a proper Netwatch
local LocNetWatchHost 1.1.1.1;
local LocNetWatchHostComment "RePowerUSB";

# Still is status down?
local LocStatus [/tool netwatch get [find host=$LocNetWatchHost comment=$LocNetWatchHostComment ] status];
if ($LocStatus != "down") do={/quit;}

# Convert the Netwatch SINCE to separate date and time of current down-time.
local LocSince  [/tool netwatch get [find host=$LocNetWatchHost comment=$LocNetWatchHostComment status=down ] since];
local LocSinceDate ([/pick $LocSince 0 11]);
local LocSinceTime ([/pick $LocSince 12 20]);

# Add action to future via scheduler
/system scheduler remove [find where name~"SiBexRePowerUSBv"];

# Try MAIN ACTION 1 - RePower USB port

local SiBCrossMid [$SiBFixDateTime $LocSinceDate $LocSinceTime 5m ];
local SiBStartDate [pick $SiBCrossMid 0 11];
local SiBStartTime [pick $SiBCrossMid 12 20];
/system scheduler add name=SiBexRePowerUSBv1 on-event={/system routerboard usb power-reset duration=3;} start-date=$SiBStartDate start-time=$SiBStartTime;

# Try MAIN ACTION 2 - ReEnable LTE interface

local SiBCrossMid [$SiBFixDateTime $LocSinceDate $LocSinceTime 8m ];
local SiBStartDate [pick $SiBCrossMid 0 11];
local SiBStartTime [pick $SiBCrossMid 12 20];
/system scheduler add name=SiBexRePowerUSBv2 on-event={/interface lte disable [find]; delay 3s; /interface lte enable [find];} start-date=$SiBStartDate start-time=$SiBStartTime;

# Try MAIN ACTION 3 - Reboot MikroTik RouterBoard

local SiBCrossMid [$SiBFixDateTime $LocSinceDate $LocSinceTime 11m ];
local SiBStartDate [pick $SiBCrossMid 0 11];
local SiBStartTime [pick $SiBCrossMid 12 20];
/system scheduler add name=SiBexRePowerUSBv3 on-event={/system reboot;} start-date=$SiBStartDate start-time=$SiBStartTime;

log error "stop Netwatch DOWN-script, Future action are scheduled";
.
This is working of few RouterOS with USB/Ethernet LTE and works very well. I hope anyone can use it because I cannot found at Forum better script and this post is the best to publish answer.
Source at GitHub too.
Last edited by SiB on Thu Aug 29, 2019 1:39 am, edited 1 time in total.
 
User avatar
Jotne
Forum Guru
Forum Guru
Posts: 3297
Joined: Sat Dec 24, 2016 11:17 am
Location: Magrathean

Re: Script to Test WAN and Reset USB Power on Down?

Mon Aug 26, 2019 12:18 pm

Here is one big problem with ping.


Router Interface 1 (Public IP 1) ----------- ISP 1 DG --------------Internet
Router Interface 2 (Public IP 2) ----------- ISP 2 DG --------------Internet

Lets say you have if1 as default gw and set a ping to ISP1 IP to see if he his up or down.
Then line to IPS1 goes down and system fail over to IPS2.
Your ping to test if line is up by ping ISP1 will still answer, since you reach ISP1 by going trough IPS2 - Internet - ISP
So line will think its up and fail back.
 
User avatar
SiB
Forum Guru
Forum Guru
Posts: 1888
Joined: Sun Jan 06, 2013 11:19 pm
Location: Poland

Re: Script to Test WAN and Reset USB Power on Down?

Mon Aug 26, 2019 1:08 pm

Here is one big problem with ping.
Not only one problem but this is a Netwatch limitation's and I NOTE about it.
I just answer at question via author of this post "Script to Test WAN and Reset USB Power on Down?" in better way.

Any MultiWan situation like separated route table, own src-address, fast flapping of ISP, detection with recursive lookup etc. are not describe by autor of this post.

Who is online

Users browsing this forum: Bing [Bot], dandu, saied and 26 guests