Community discussions

 
User avatar
janisk
MikroTik Support
MikroTik Support
Topic Author
Posts: 6283
Joined: Tue Feb 14, 2006 9:46 am
Location: Riga, Latvia

Useful scripts

Wed Mar 31, 2010 8:43 am

I will try to get all the useful links to threads to look at when some script is needed, that is not yet in wiki or is in wiki, just to get them not buried under loads other posts.

Check time of the post, to make some link to RouterOS version these where created for.
 
namo
Long time Member
Long time Member
Posts: 530
Joined: Sat Oct 03, 2009 4:44 pm

Re: Useful scripts

Tue Dec 14, 2010 5:10 am

thank you janisk. It also useful to mention the RouterOS version that the script work with because sometimes I found old scripts for v2.9 and they don't work with v4.14
 
User avatar
janisk
MikroTik Support
MikroTik Support
Topic Author
Posts: 6283
Joined: Tue Feb 14, 2006 9:46 am
Location: Riga, Latvia

Re: Useful scripts

Thu Jan 05, 2012 12:26 pm

in that case take CLI script editor (inside RouterOS) and edit script in there. Most of the syntax changes can be caught using that. F5 to refresh highlighting.
 
angboontiong
Forum Guru
Forum Guru
Posts: 1115
Joined: Fri Jan 16, 2009 9:59 am

Re: Useful scripts

Sat Mar 17, 2012 1:42 pm

in that case take CLI script editor (inside RouterOS) and edit script in there. Most of the syntax changes can be caught using that. F5 to refresh highlighting.
all version have this editor?
where it's located?

thanks.
 
User avatar
janisk
MikroTik Support
MikroTik Support
Topic Author
Posts: 6283
Joined: Tue Feb 14, 2006 9:46 am
Location: Riga, Latvia

Re: Useful scripts

Wed Mar 28, 2012 10:20 am

all RouterOS have this.
in CLI - /system script edit <script-name> source
 
Nima1394
just joined
Posts: 1
Joined: Tue Jun 19, 2012 12:10 pm

Re: The Scrip does not work!

Tue Jun 19, 2012 12:33 pm

Hi guys
Why the scrip does not work?!
set[/ip route find dst 0.0.0.0] gateway 10.0.0.1
this command mentioned in wiki.mikrotik:
http://wiki.mikrotik.com/wiki/Manual:Tools/Netwatch
after enter the command, notting happen and the default route doesn't change.
I want to write a script to change the default route gateway.
 
rdc
just joined
Posts: 10
Joined: Wed Jan 09, 2013 3:40 am

Re: Useful scripts

Wed Jan 09, 2013 12:50 pm

I don't know where to post this but this is by far the best place to post it. Basically what the script does is that it will check for dynamic leases on my dhcp server, take their mac addresses and check it against firewall filter. If it's not there it will add it and drop everything that's coming from those mac addresses. I'm using this to prevent users from using my internet bandwidth without prior permission and they just happen to know my wireless key from a colleague.

The script below is tested to work on 2.9.x:
:foreach i in=[/ip dhcp-server lease find dynamic=yes] do={
   :set dynamicMAC [/ip dhcp-server lease get $i mac-address];
   :set dynamicHOST [/ip dhcp-server lease get $i host-name];
   :set macfound [/ip firewall filter find src-mac-address=$dynamicMAC];

    :if ($macfound != "") do={
        :log info ($dynamicMAC. " already filtered")
    } else= {
        /ip firewall filter add chain=forward src-mac-address=$dynamicMAC action=drop comment=($dynamicHOST . " - " . $dynamicMAC . " Unregistered device")
        :log info ("Added " . $dynamicMAC. " to firewall filter")
    }
}
The code below is tested to work on 5.19:
:foreach i in=[/ip dhcp-server lease find dynamic] do={
   :local dynamicMAC [/ip dhcp-server lease get $i mac-address];
   :local dynamicHOST [/ip dhcp-server lease get $i host-name];
   :local macfound [/ip firewall filter find src-mac-address=$dynamicMAC];

    :if ($macfound != "") do={
        :log info ($dynamicMAC. " already filtered")
    } else= {
        /ip firewall filter add chain=forward src-mac-address=$dynamicMAC action=drop comment=($dynamicHOST . " - " . $dynamicMAC . " Unregistered device")
        :log info ("Added " . $dynamicMAC. " to firewall filter")
    }
}
Good luck!
 
solelunauno
Member Candidate
Member Candidate
Posts: 107
Joined: Mon Jul 16, 2012 7:00 pm
Location: Roseto Capo Spulico CS Italy
Contact:

backup to FTP with sd-card

Fri Aug 23, 2013 12:55 pm

Hallo,
i made this simple script in order to backup daily the router settings and usermanager database, using sd-card as buffer in order to reduce router nand's use.
It is especially useful when yuo plan to enlarge usermanager database until gigabyte size, making backup into router's nand not more possible.
I'll write also another script to "rebuild" database and logs every week, to reduce backup's size.
This script will erase always the same two files, in order to have always the last good version in ftp.

#automated System
:log info message=System_Export_started;
:local exportname ([/system identity get name].".rsc");
:local UMname ([/system identity get name].".umb");
export compact file=micro-sd/exportSy.rsc;
/tool user-manager database save name=micro-sd/backupUM.umb;
:log info message=System_Export_finished;
# Upload the System Backup to External FTP;
/tool fetch address=192.168.1.1 port=21 src-path=micro-sd/exportSy.rsc upload=yes \
user=FTPuser mode=ftp password="FTPpassword" dst-path=$exportname;
/tool fetch address=192.168.1.1 port=21 src-path=micro-sd/backupUM.umb upload=yes \
user=FTPuser mode=ftp password="FTPpassword" dst-path=$UMname;
/file remove micro-sd/backupUM.umb;
/file remove micro-sd/exportSy.rsc;
:log info message=System_Export_uploaded;

where you have to put your ftp server address instead of "192.168.1.1" and your FTP user and password.
I take inspiration from this post: http://forum.mikrotik.com/viewtopic.php?f=9&t=52371 and I hope it will be useful for someone. :D
It works with RouterOS 6.2 .
SL1 Systems srl MTCNA MTCRE
 
nurmia
newbie
Posts: 28
Joined: Thu Oct 03, 2013 4:34 pm

Re: Useful scripts

Sun Nov 10, 2013 10:50 am

thank you janisk for good info. your post is very helpful for me.
 
User avatar
rextended
Forum Guru
Forum Guru
Posts: 2946
Joined: Tue Feb 25, 2014 12:49 pm
Location: Capalbio, Tuscany, Italy

Re: Useful scripts

Wed Mar 19, 2014 10:25 pm

I open another thread for my script:

Check locked PPPOE, PPTP, L2TP, SSTP, OVPN, and PPP connections

http://forum.mikrotik.com/viewtopic.php?f=9&t=83132

Remember to add Karma if you use my script!
Also remember to report any bug, thanks.
Last edited by rextended on Tue Mar 25, 2014 11:30 pm, edited 2 times in total.
I'm Italian, not English. Sorry for my imperfect grammar.
 
User avatar
rextended
Forum Guru
Forum Guru
Posts: 2946
Joined: Tue Feb 25, 2014 12:49 pm
Location: Capalbio, Tuscany, Italy

Re: Useful scripts

Tue Mar 25, 2014 11:13 pm

I open another thread for my script:

How to ***really*** block invalid TCP and UDP packet

http://forum.mikrotik.com/viewtopic.php?f=9&t=83387

Remember to add Karma if you use my script!
Also remember to report any bug, thanks.
I'm Italian, not English. Sorry for my imperfect grammar.
 
User avatar
cdiedrich
Forum Veteran
Forum Veteran
Posts: 896
Joined: Thu Feb 13, 2014 2:03 pm
Location: Basel, Switzerland // Bremen, Germany
Contact:

Re: Useful scripts

Tue Apr 29, 2014 11:26 am

Here's one I just wrote to centrally push new (beta) firmwares to our CAPsMAN managed Wireless system in a batch:

ros code

/system script
add name=pushupdate policy=ftp,read,write,policy,test,winbox,password,sniff,sensitive,api source="
:foreach i in=[/ip firewall address-list find list=accesspoints] do={
[/tool fetch  address=[/ip firewall address-list  get $i address] mode=ftp user=login password=password src-path=updates/wireless-fp-6.13rc7-mipsbe.npk dst-path=wireless-fp-6.13rc7-mipsbe.npk upload=yes];
[/tool fetch  address=[/ip firewall address-list  get $i address] mode=ftp user=login password=password src-path=updates/routeros-mipsbe-6.13rc7.npk dst-path=routeros-mipsbe-6.13rc7.npk upload=yes];
[/tool fetch  address=[/ip firewall address-list  get $i address] mode=ftp user=login password=password src-path=updates/reboot.rsc dst-path=reboot.auto.rsc upload=yes];
}
I have all the Access Points in the address list "accesspoints".
The filenames are hard coded on purpose to keep an eye on the versions.

The reboot.rsc script looks like this:

ros code

:file remove reboot.auto.rsc
:log warning "Firmware upgrade initiated"
:delay 1s
:system reboot
...(Warnings and errors are logged to disk, everything else to memory only, this is why I issue a warning).

In case anything goes wrong, I have a downgrade script with 6.12 in place as well.
The reboot script then invokes /system package downgrade instead of reboot.

Maybe this is helpful for someone.

Cheers
-Chris
Christopher Diedrich
MTCNA, MTCUME, MTCWE
Basel, Switzerland
Bremen, Germany

There are 10 types of people: Those who understand binary and those who don't.
There are two types of people: Those who can extrapolate from incomplete data
 
plisken
Forum Guru
Forum Guru
Posts: 2399
Joined: Sun May 15, 2011 12:24 am
Location: Belgium
Contact:

Re: Useful scripts

Sat May 10, 2014 1:04 pm

Where and how set you a list with registered users?

I don't know where to post this but this is by far the best place to post it. Basically what the script does is that it will check for dynamic leases on my dhcp server, take their mac addresses and check it against firewall filter. If it's not there it will add it and drop everything that's coming from those mac addresses. I'm using this to prevent users from using my internet bandwidth without prior permission and they just happen to know my wireless key from a colleague.

The script below is tested to work on 2.9.x:
:foreach i in=[/ip dhcp-server lease find dynamic=yes] do={
   :set dynamicMAC [/ip dhcp-server lease get $i mac-address];
   :set dynamicHOST [/ip dhcp-server lease get $i host-name];
   :set macfound [/ip firewall filter find src-mac-address=$dynamicMAC];

    :if ($macfound != "") do={
        :log info ($dynamicMAC. " already filtered")
    } else= {
        /ip firewall filter add chain=forward src-mac-address=$dynamicMAC action=drop comment=($dynamicHOST . " - " . $dynamicMAC . " Unregistered device")
        :log info ("Added " . $dynamicMAC. " to firewall filter")
    }
}
The code below is tested to work on 5.19:
:foreach i in=[/ip dhcp-server lease find dynamic] do={
   :local dynamicMAC [/ip dhcp-server lease get $i mac-address];
   :local dynamicHOST [/ip dhcp-server lease get $i host-name];
   :local macfound [/ip firewall filter find src-mac-address=$dynamicMAC];

    :if ($macfound != "") do={
        :log info ($dynamicMAC. " already filtered")
    } else= {
        /ip firewall filter add chain=forward src-mac-address=$dynamicMAC action=drop comment=($dynamicHOST . " - " . $dynamicMAC . " Unregistered device")
        :log info ("Added " . $dynamicMAC. " to firewall filter")
    }
}
Good luck!
 
User avatar
rextended
Forum Guru
Forum Guru
Posts: 2946
Joined: Tue Feb 25, 2014 12:49 pm
Location: Capalbio, Tuscany, Italy

Re: Useful scripts

Sat May 10, 2014 5:00 pm

Add manually the devices on DHCP leases...
I'm Italian, not English. Sorry for my imperfect grammar.
 
IntrusDave
Forum Guru
Forum Guru
Posts: 1282
Joined: Fri May 09, 2014 4:36 am
Location: Rancho Cucamonga, CA

Re: Useful scripts

Fri Jul 24, 2015 10:41 am

Script to download a current address-list to blacklist known botnets, spammers, scammers and C&C servers.
http://forum.mikrotik.com/viewtopic.php?f=9&t=98804
David Joyce
Network & Security Engineer
Intrus Technologies, LLC.
Rancho Cucamonga, CA, USA
 
User avatar
Cha0s
Forum Veteran
Forum Veteran
Posts: 882
Joined: Tue Oct 11, 2005 4:53 pm

Re: Useful scripts

Thu Aug 13, 2015 7:00 pm

Script to send notifications to multiple email addresses for multiple BGP Peers if their status is not 'established'
http://forum.mikrotik.com/viewtopic.php ... 04#p494204
 
gammy69er
newbie
Posts: 46
Joined: Sun May 18, 2014 3:01 am

Re: Useful scripts

Fri Aug 14, 2015 7:16 am

have Just added a Script for Hotspot Data Limit

http://forum.mikrotik.com/viewtopic.php?f=9&t=99515

Sets Data Limit On Login - no scripted monitoring required - and disconnects once data is used
 
User avatar
favincen
just joined
Posts: 21
Joined: Mon Jun 08, 2015 1:56 pm
Location: Grenoble, France

Re: Useful scripts

Fri Aug 28, 2015 2:00 pm

all RouterOS have this.
in CLI - /system script edit <script-name> source
Beware that this won't work if your script is above 4Kb ! (See this post ).
So it only works for small script... :evil:
If you consider this post useful, you can tell by rating it positively... Thanks ! 8)
 
jfrawley
just joined
Posts: 3
Joined: Sun Jan 10, 2016 9:16 pm

Re: Useful scripts

Sun Jan 10, 2016 9:26 pm

Looking to edit my Voltage report script I have been using, currently it is set to send email of report daily at 11pm, I am trying to change to 8am but I have been getting negative hour results such as -1 -2 -3 etc. I made two changes and am going to see what happens tomorrow but if you know of simple way to fix please let me know- below is the script I been using from the site (2 scripts). I am not script smart but am trying to figure some of this out, just would like reports at 8am rather than 11pm

# I changed a line below from 23 - $x to 08 + $x in hopes to get positive numbers
:global highvolt
:global lowvolt
:global hivolttime
:global lovolttime
:global starttime
:global vh
:local tvolt
:local thisbox [/system identity get name]
:local thisdate [/system clock get date]
:local thishour
:local emessage "Daily voltage report for $thisbox on $thisdate\n\n"
:if ([:len $vh] > 0) do={
:for x from=0 to=([:len $vh]-1) step=1 do={
:set tvolt [:tostr [:pick $vh $x]]
:set thishour [:tostr (08 + $x)]
:while ([:len $thishour] < 2) do={:set thishour ("0" . $thishour)}
:set emessage ($emessage . $thishour . ":00 = " . [:pick $tvolt 0 2] . "." . [:pick $tvolt 2 3] . "\n")
}
:set emessage ($emessage . "\nSince voltmonitor started on " . $starttime . "\n")
:set tvolt [:tostr $highvolt]
:set emessage ($emessage . "Maximum = " . [:pick $tvolt 0 2] . "." . [:pick $tvolt 2 3] . "v at " . $hivolttime . "\n")
:set tvolt [:tostr $lowvolt]
:set emessage ($emessage . "Minimum = " . [:pick $tvolt 0 2] . "." . [:pick $tvolt 2 3] . "v at " . $lovolttime . "\n")
# set email address in next line
/tool e-mail send to="myemail" subject="$thisbox Voltage Report" body=$emessage}

# remark out the next line for testing to avoid resetting the voltage array
:set vh


##########################################################################
Volt monitor script-
# I changed the line below for when to run the report script from thishour 23 to thishour 08

#set lowvoltalarm to desired alarm voltage in tenths of a volt. 118 = 11.8v # the +015 is for volt offset of real volts
:global lowvoltalarm 225
:global highvolt
:global lowvolt
:global starttime
:global hivolttime
:global lovolttime
:global vh
:local thisbox [/system identity get name]
:global voltage ([/system health get voltage] + 015)
:local thistime [/system clock get time]
:local thisdate [/system clock get date]
:local thishour [:pick $thistime 0 2]
:local emessage ($thisbox . " voltage is " . [:pick $voltage 0 2] . "." . [:pick $voltage 2 3])
:if ([:len $lowvolt] < 1) do={:set lowvolt 999; :set highvolt 0}
:if ($voltage <= $lowvoltalarm) do={/tool e-mail send to="mycelltext" subject="$thisbox low voltage" body=$emessage}
:if ($voltage <= $lowvoltalarm) do={/tool e-mail send to="hiscelltext" subject="$thisbox low voltage" body=$emessage}
:if ($voltage > $highvolt) do={:set highvolt $voltage; :set hivolttime ($thistime . " " . $thisdate)}
:if ($voltage < $lowvolt) do={:set lowvolt $voltage; :set lovolttime ($thistime . " " . $thisdate)}
:if ([:len $vh] > 0) do={:set vh ([:toarray $voltage] + $vh)} else={:set vh [:toarray $voltage]}
:if ([:len $starttime] < 1) do={:set starttime ($thistime . " " . $thisdate)}
:if ($thishour = "08") do={:execute voltreport}
Jason
Leader Comm.
Idaho USA
 
Trezona
Frequent Visitor
Frequent Visitor
Posts: 59
Joined: Wed Feb 22, 2006 6:34 pm

Re: Useful scripts

Thu Jan 21, 2016 1:08 pm

Hello jfrawley,

Did you get your voltage monitoring script to work on 6.33.5?
I also have a similar votage monitoring script to yours, i have it working great on 6.29,
but i cannot get it to work on any version higher than 6.30...

Here is my script:

#set lowvoltalarm to desired alarm voltage in tenths of a volt. 125 = 12.5v
:global lowvoltalarm 200
:global highvoltalarm 280
:global highvolt
:global lowvolt
:global starttime
:global hivolttime
:global lovolttime
:global vh
:local thisbox [/system identity get name]
:global voltage [/system health get voltage]
:local thistime [/system clock get time]
:local thisdate [/system clock get date]
:local thishour [:pick $thistime 0 2]
:local emessage ($thisbox . " voltage is: " . [:pick $voltage 0 2] . "." . [:pick $voltage 2 3])
:if ([:len $lowvolt] < 1) do={:set lowvolt 999; :set highvolt 0}
# set your email address in the next line
:if ($voltage <= $lowvoltalarm) do={/tool e-mail send to="test@test.com" subject="$thisbox Voltage Statistics" body=$emessage}
:if ($voltage >= $highvoltalarm) do={/tool e-mail send to="test@test.com" subject="$thisbox Voltage Statistics" body=$emessage}
:if ($voltage > $highvolt) do={:set highvolt $voltage; :set hivolttime ($thistime . " " . $thisdate)}
:if ($voltage < $lowvolt) do={:set lowvolt $voltage; :set lovolttime ($thistime . " " . $thisdate)}
:if ([:len $vh] > 0) do={:set vh ([:toarray $voltage] + $vh)} else={:set vh [:toarray $voltage]}
:if ([:len $starttime] < 1) do={:set starttime ($thistime . " " . $thisdate)}
:if ($thishour = "23") do={:execute voltreport}

I run this every 30 minutes.

Could somone one please tell me why this now does not work on all versions higher than 6.30?

Thanks.
 
hamster922
just joined
Posts: 7
Joined: Thu Jul 08, 2010 4:58 pm

Re: Useful scripts

Sat Apr 09, 2016 7:37 pm

Same Problem here, can't get the same script working on 6.30.4

Anyone?
 
jambopk
just joined
Posts: 1
Joined: Fri Apr 15, 2016 8:44 am
Location: karachi, Pakistan
Contact:

Re: Useful scripts

Fri Apr 15, 2016 8:54 am

thank you Janisk. Very usful scripts for RouterOS version which i am using and work effectively.
Visit my website Logonado
 
drnitinarora
newbie
Posts: 32
Joined: Fri Sep 25, 2009 6:08 pm

Re: Useful scripts

Sun May 15, 2016 1:48 pm

Is there a way we can restrict the Active user sessions in Hotspot?

Eg.
- If we have 100 connected hosts to mikrotik
- If we set active users to 10 , then only 10 active users are allowed to login out of 100 connected hosts at any given time.

Thanks in anticipation
 
alexathinaios
just joined
Posts: 4
Joined: Sat Jun 14, 2014 2:46 am
Contact:

Re: Useful scripts

Thu Jun 30, 2016 11:51 am

Hello there,

Here is mine if you have pppoe client and pptp server on your gateways for sharing internet and your adsl lines needs an eye on them.

http://forum.mikrotik.com/viewtopic.php ... 1fc574e085
Life is Better With Mikrotik!
 
sosobobo
just joined
Posts: 5
Joined: Sun Sep 11, 2016 1:25 pm
Contact:

Re: Useful scripts

Sun Sep 11, 2016 1:50 pm

thank you janisk. It also useful to mention the RouterOS version that the script work with because sometimes I found old scripts for v2.9 and they don't work with v4.14
COmmpletely agree! It would be really helpful! For me it also did not work with v4.14
 
User avatar
koolandrew
just joined
Posts: 18
Joined: Tue Dec 06, 2011 7:20 pm
Location: Toronto
Contact:

WAN Failover Script using Netwatch

Wed Oct 05, 2016 10:34 pm

Please help me with this script as i spent a crazy amount of time and it still doesnt completely work.
. I have tried so many ways to make this work, and i can get Netwatch to work beautifully when the first route goes down, but it doesnt work when the route comes back up again. I have borrowed from many different forums, the largest part from Steve Discher..

I have tried to change the distance, enable=true, disable=false, enabled=true, enabled=yes, and everything else i could think of but nothing works to make the primary route, the primary route.

/ip firewall filter
add action=drop chain=output comment=\
"Drop pings to 4.2.2.4 if they go through PROVIDER2" dst-address=4.2.2.4 \
out-interface=ether2-gateway
/ip route
add comment=PROVIDER1 distance=1 gateway=192.168.2.1 scope=11
add comment=PROVIDER2 distance=10 gateway=192.168.3.1
add comment="Force test pings through PROVIDER1" distance=1 dst-address=\
4.2.2.4/32 gateway=192.168.2.1

Here is my first netwatch script, it works great until provider 2 starts working, and the distance remains at 20, so it doesnt work, and no emails get sent.

/tool netwatch
add comment=CheckCon down-script="/ip route set [find comment=\"PROVIDER1\"] d\
istance=20\r\
\n/ip route set [find comment=\"PROVIDER2\"] disabled=no\r\
\n/tool e-mail send to=\"andrew.wells@xx.xxx\" body=\"Connection with\
\_PROVIDER1 Lost, Switched to PROVIDER2\" subject=\"Lost connection with P\
ROVIDER1\"\r\
\n/tool e-mail send to=\"andrewwells@xx.xxx\" body=\"Connection with \
PROVIDER1 Lost, Switched to PROVIDER2\" subject=\"Lost connection with PRO\
VIDER1\"\r\
\n:log error \"Primary internet connection down\"\r\
\n/ ip firewall connection remove [/ip firewall connection find dst-addres\
s~\"xx.xxx.137.117:5060\"]" host=4.2.2.4 interval=5s timeout=2s \
up-script="/ip route set [find comment=\"PROVIDER1\"] distance=1\r\
\n/ip route set [find comment=\"PROVIDER2\"] disabled=no\r\
\n/tool e-mail send to=\"andrew.wells@xx.xxx\"\r\
\nbody=\"Connection with PROVIDER1 Regained, Switched back to PROVIDER1\" \
subject=\"Regained connection with PROVIDER1\"\r\
\n/tool e-mail send to=\"andrewwells@xx.xxx\"\r\
\nbody=\"Connection with PROVIDER1 Regained, Switched back to PROVIDER1\" \
subject=\"Regained connection with PROVIDER1\"\r\
\n/ ip firewall connection remove [/ip firewall connection find dst-addres\
s~\"xx.xxx.137.117:5060\"]"

Here is my 80th attempt, with changes to the up script, and i have tried everything i could find on the forums. Now the route remains disabled, and again, no emails go out.

/tool netwatch
add comment=CheckCon down-script="/ip route set [find comment=\"PROVIDER1\"] d\
isabled=yes\r\
\n/ip route set [find comment=\"PROVIDER2\"] disabled=no\r\
\n/tool e-mail send to=\"andrew.wells@xx.xxx\" body=\"Connection with\
\_PROVIDER1 Lost, Switched to PROVIDER2\" subject=\"Lost connection with P\
ROVIDER1\"\r\
\n/tool e-mail send to=\"andrewwells@xx.xxx\" body=\"Connection with \
PROVIDER1 Lost, Switched to PROVIDER2\" subject=\"Lost connection with PRO\
VIDER1\"\r\
\n:log error \"Primary internet connection down\"\r\
\n/ ip firewall connection remove [/ip firewall connection find dst-addres\
s~\"xx.xxx.137.117:5060\"]\r\
\n/ ip firewall connection remove [/ip firewall connection find dst-addres\
s~\"xx.xxx.137.116:5060\"]" host=4.2.2.4 interval=5s timeout=2s \
up-script="/ip route get [find comment=\"PROVIDER1\"] disabled=true\r\
\n/ip route set [find comment=\"PROVIDER1\"] disabled=no\r\
\n/ip route set [find comment=\"PROVIDER2\"] disabled=no\r\
\n/tool e-mail send to=\"andrew.wells@xx.xxx\"\r\
\nbody=\"Connection with PROVIDER1 Regained, Switched back to PROVIDER1\" \
subject=\"Regained connection with PROVIDER1\"\r\
\n/tool e-mail send to=\"andrewwells@xx.xxx\"\r\
\nbody=\"Connection with PROVIDER1 Regained, Switched back to PROVIDER1\" \
subject=\"Regained connection with PROVIDER1\"\r\
\n/ ip firewall connection remove [/ip firewall connection find dst-addres\
s~\"xx.xxx.137.117:5060\"]\r\
\n/ ip firewall connection remove [/ip firewall connection find dst-addres\
s~\"xx.xxx.137.116:5060\"]"
 
peacequarters
just joined
Posts: 1
Joined: Wed Nov 16, 2016 12:46 pm
Contact:

Re: Useful scripts

Wed Nov 16, 2016 12:51 pm

thank you Janisk. Very usful scripts for RouterOS version which i am using and work effectively.
Visit LIASC
 
fernando1787
just joined
Posts: 9
Joined: Mon Apr 11, 2016 6:32 pm

/ip route add comment=PROVIDER1 distance=1 gateway=192.168.2.1 scope=11 add comment=PROVIDER2 distance=10 gateway=192.16

Wed Jan 25, 2017 11:38 pm

Please help me with this script as i spent a crazy amount of time and it still doesnt completely work.
. I have tried so many ways to make this work, and i can get Netwatch to work beautifully when the first route goes down, but it doesnt work when the route comes back up again. I have borrowed from many different forums, the largest part from Steve Discher..

I have tried to change the distance, enable=true, disable=false, enabled=true, enabled=yes, and everything else i could think of but nothing works to make the primary route, the primary route.

/ip firewall filter
add action=drop chain=output comment=\
"Drop pings to 4.2.2.4 if they go through PROVIDER2" dst-address=4.2.2.4 \
out-interface=ether2-gateway
/ip route
add comment=PROVIDER1 distance=1 gateway=192.168.2.1 scope=11
add comment=PROVIDER2 distance=10 gateway=192.168.3.1
add comment="Force test pings through PROVIDER1" distance=1 dst-address=\
4.2.2.4/32 gateway=192.168.2.1

Here is my first netwatch script, it works great until provider 2 starts working, and the distance remains at 20, so it doesnt work, and no emails get sent.

/tool netwatch
add comment=CheckCon down-script="/ip route set [find comment=\"PROVIDER1\"] d\
istance=20\r\
\n/ip route set [find comment=\"PROVIDER2\"] disabled=no\r\
\n/tool e-mail send to=\"andrew.wells@xx.xxx\" body=\"Connection with\
\_PROVIDER1 Lost, Switched to PROVIDER2\" subject=\"Lost connection with P\
ROVIDER1\"\r\
\n/tool e-mail send to=\"andrewwells@xx.xxx\" body=\"Connection with \
PROVIDER1 Lost, Switched to PROVIDER2\" subject=\"Lost connection with PRO\
VIDER1\"\r\
\n:log error \"Primary internet connection down\"\r\
\n/ ip firewall connection remove [/ip firewall connection find dst-addres\
s~\"xx.xxx.137.117:5060\"]" host=4.2.2.4 interval=5s timeout=2s \
up-script="/ip route set [find comment=\"PROVIDER1\"] distance=1\r\
\n/ip route set [find comment=\"PROVIDER2\"] disabled=no\r\
\n/tool e-mail send to=\"andrew.wells@xx.xxx\"\r\
\nbody=\"Connection with PROVIDER1 Regained, Switched back to PROVIDER1\" \
subject=\"Regained connection with PROVIDER1\"\r\
\n/tool e-mail send to=\"andrewwells@xx.xxx\"\r\
\nbody=\"Connection with PROVIDER1 Regained, Switched back to PROVIDER1\" \
subject=\"Regained connection with PROVIDER1\"\r\
\n/ ip firewall connection remove [/ip firewall connection find dst-addres\
s~\"xx.xxx.137.117:5060\"]"

Here is my 80th attempt, with changes to the up script, and i have tried everything i could find on the forums. Now the route remains disabled, and again, no emails go out.

/tool netwatch
add comment=CheckCon down-script="/ip route set [find comment=\"PROVIDER1\"] d\
isabled=yes\r\
\n/ip route set [find comment=\"PROVIDER2\"] disabled=no\r\
\n/tool e-mail send to=\"andrew.wells@xx.xxx\" body=\"Connection with\
\_PROVIDER1 Lost, Switched to PROVIDER2\" subject=\"Lost connection with P\
ROVIDER1\"\r\
\n/tool e-mail send to=\"andrewwells@xx.xxx\" body=\"Connection with \
PROVIDER1 Lost, Switched to PROVIDER2\" subject=\"Lost connection with PRO\
VIDER1\"\r\
\n:log error \"Primary internet connection down\"\r\
\n/ ip firewall connection remove [/ip firewall connection find dst-addres\
s~\"xx.xxx.137.117:5060\"]\r\
\n/ ip firewall connection remove [/ip firewall connection find dst-addres\
s~\"xx.xxx.137.116:5060\"]" host=4.2.2.4 interval=5s timeout=2s \
up-script="/ip route get [find comment=\"PROVIDER1\"] disabled=true\r\
\n/ip route set [find comment=\"PROVIDER1\"] disabled=no\r\
\n/ip route set [find comment=\"PROVIDER2\"] disabled=no\r\
\n/tool e-mail send to=\"andrew.wells@xx.xxx\"\r\
\nbody=\"Connection with PROVIDER1 Regained, Switched back to PROVIDER1\" \
subject=\"Regained connection with PROVIDER1\"\r\
\n/tool e-mail send to=\"andrewwells@xx.xxx\"\r\
\nbody=\"Connection with PROVIDER1 Regained, Switched back to PROVIDER1\" \
subject=\"Regained connection with PROVIDER1\"\r\
\n/ ip firewall connection remove [/ip firewall connection find dst-addres\
s~\"xx.xxx.137.117:5060\"]\r\
\n/ ip firewall connection remove [/ip firewall connection find dst-addres\
s~\"xx.xxx.137.116:5060\"]"
 
TechDan1
just joined
Posts: 1
Joined: Wed Aug 23, 2017 9:31 am

Re: Useful scripts

Wed Aug 23, 2017 9:34 am

Thank you so much for sharing. I have found so many useful information up there.
 
User avatar
horhay
newbie
Posts: 28
Joined: Sat Jun 20, 2015 7:19 pm
Location: Ontario, Canada
Contact:

Re: Useful scripts

Mon Aug 28, 2017 8:50 pm

Prior to the addition of fasttrack you could remove all firewall filters with
/ip firewall filter
rem [find]
Now that we have fasttrack you must use this
/ip firewall filter
rem [find where !dynamic]
 
CTSsean
just joined
Posts: 23
Joined: Fri Sep 15, 2017 12:56 pm

Re: Useful scripts

Sun Nov 05, 2017 8:43 pm

Here are my FreeDNS script for updating a FreeDNS domain, when you have more than 1 FreeDNS domain.
It also posts the start and stop of the script in the log. It was originally created by LESHIY_ODESSA, but I've improved it by adding some error checking and making this work when you have more than 1 FreenDNS domain. Also, instead of checking the wan interface only, I check the ether interface first and then check the web to see what the IP shows.
The only catch 22 is if you force a change of the FreeDNS ip on their site and don't restart your router/update the variable, the router will still have the old value and will never update unless your actual ip changes.

If you are double nat'd, you'll need to modify it to fit that environment.

:log warning ("DNS script begin")
##############    Script FreeDNS.afraid.org   ##################
##############    CREATED LESHIY_ODESSA   ##################
##############    Improved by SEAN SCARFO  ##################
# Specify your domain or subdomain.
:global "dns-domain" "whatever.woot.me"

# Define IP checker website variable.  Any website that returns only the ip address in text format. examples listed
#https://www.trackip.net/ip/
#http://wgetip.com/
#https://api.ipify.org/
#If not pointing to a specific file, must end in a /
# Case sensitive.
:global "wanChecker" "http://wgetip.com/"

#specify your internet interface.  naming does not have to be exact as long as it has "ether" in the name
:global "wanInterface" "ether1"


# Specify the "Direct URL", which is https://freedns.afraid.org/dynamic/
# In front of the sign "?" put a backslash "\".
:global "direct-url" "https://freedns.afraid.org/dynamic/update.php\?98675985876548765486547654jhdf"

# Specify the URL API "ASCII"
# Log in under your account and open the page https://freedns.afraid.org/api/
# Then copy the URL of your site - Available API Interfaces : ASCII (!!! NOT XML !!!)
# ATTENTION!!!! Before the question mark, put a backslash "\".
:global "api-url" "https://freedns.afraid.org/api/\?action=getdyndns&v=2&sha=87587657865hjgfhgfjhgf"


       
# !!!!!!!!!!!!!!!!! Nothing more do not need to edit!!!!!!!!!!!!!!!!!
:global "current-ip"
:global "dns-domain-ip"
:if ([:len $"current-ip"] <7) do={
    :log error ("current-ip variable has no value, setting it to 1.1.1.1");
    :global "current-ip" 1.1.1.1;
} else={
    :log warning ("current IP variable exists and has a value")
#pause for 1 seconds
:delay 1

#Fetch Current IP from ether1
:global "current-ip" [/ip address get value-name=address [find interface~$"wanInterface"]]
:global "current-ip-endloc" ([:len $"current-ip"] -3)
:global "current-ip" [:pick $"current-ip" 0 $"current-ip-endloc"]

# Compare global IP variables
# Compare the external IP with the IP address of the DNS domain.
    :if ($"current-ip" = $"dns-domain-ip") do={
    :log warning ("current-ip matches dns-domain-ip, script is done!")
    } else={
#pause for 1 seconds
:delay 1

	:log error ("$"current-ip" does not match $"dns-domain-ip", updating IP FreeDNS")
#pause for 1 seconds
:delay 1

#Fetch Last Known IP info from WanChecker       
    /tool fetch url="$wanChecker" dst-path="/wanCheckerfile.txt"
#pause for 1 seconds
:delay 1

# Find the current IP address on the external interface
    :global "current-ip" [/file get wanCheckerfile.txt contents]
#pause for 1 seconds
:delay 1
	
#Fetch Last Known IP info from FreeDNS       
    /tool fetch url=$"api-url" dst-path="/freedns.txt"
#pause for 1 seconds
:delay 1

# Find out the IP address of the domain using the API and parsing.
# Split the file
    :local "result" [/file get freedns.txt contents]
    :local "startloc" ([:find $result $"dns-domain"] + [:len $"dns-domain"] + 1)
    :local "endloc" ([:find $"result" "https" [:find $result $"dns-domain"]] -1)
    :global "dns-domain-ip" [:pick $"result" $"startloc" $"endloc"]
#pause for 1 seconds
:delay 1

# Compare global IP variables
# Compare the external IP with the IP address of the DNS domain.
    :if ($"current-ip" = $"dns-domain-ip") do={
    :log warning ("current-ip matches dns-domain-ip, script is done!")
    } else={
#pause for 1 seconds
:delay 1

# Send new IP to freedns.afraid.org our external IP by using Direct URL
    :log error ("Service Dynamic DNS: old IP address $"dns-domain-ip" for $"dns-domain" CHANGED to -> $"current-ip"")
    /tool fetch mode=https url=$"direct-url" keep-result=no
    }
}
}
:log warning ("DNS script end")
 
icosasupport
just joined
Posts: 22
Joined: Fri Oct 13, 2017 8:37 pm

Re: Useful scripts

Wed Nov 08, 2017 6:57 pm

Hi all,

Here's a script to convert strings to upper or lower

To call it simply reference the function in your code and call it:
:local replace [:parse [:system script get replace-upper-lower source]]
:set $var [$replace "convert me to upper" ] 
OR
:set $var [$replace "CONVERT ME TO LOWER" 1 ]
Just call this script 'replace-upper-lower'
:local lower [:toarray "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z"]
:local upper [:toarray "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z"]
# Pass as param 2 to toggle conversion
:local mode false
:local result
:if (($2 = "") || ($2 = nil)) do={:set $mode true}
:for idx from=0 to=([:len $1] - 1) do={ 
	:local char [:pick $1 $idx]
	:local match
	:if ($mode) do={
		:for i from=0 to=[:len $lower] do={
			:set $match ($lower->$i)
			:if ($char = $match) do={:set $char ($upper->$i)}
		}
	} else={
		:for i from=0 to=[:len $upper] do={
			:set $match ($upper->$i)
			:if ($char = $match) do={:set $char ($lower->$i)}
		}
	}
	:set $result ($result.$char)
}
:return $result
 
icosasupport
just joined
Posts: 22
Joined: Fri Oct 13, 2017 8:37 pm

Re: Useful scripts

Wed Nov 08, 2017 7:22 pm

Hey all,

Here's a script that reads a "config" file, parses it as a key:value pair and returns an array of key:value pairs with the K:V pair as an array also.
Each line of the config file represents the index value of the main array, and then each key:value pair in the array can be indexed as position zero OR position one.
This is really useful if you need your scripts to be dynamic without have to hard code certain parameters into the script itself.
We use this method so that if the config file gets replaced with updated values, the script will still function without editing it.

Sample usage:
1. Create the config file and save it to the router (example below) you can only create and use .txt files
[I do realize that the filename can have any extension. However if you use the router file commands to create the file then it will give it the extension of .TXT by default]
2. Put one key:value pair on each line, the default delimiter is : however the second parameter of the function will let you use a custom delimiter.
3. On the last line of the config file you need to have a CRLF as the termination (Note: a carriage return not the letters CRLF)
4. Reference your config file as the first parameter of the function, you can omit the .txt extension if you want

E.G monitor-api.txt file :
user:api
pass:api
protocol:https://
server:monitor.domain.local
url:/api/v0/devices
[CRLF]

In this example the :pick statement reads the value from the index of the array ($config->0) at position zero, and picks the second value in that array.
In this case we just want the username and password values, not the the key name. There are other times when both values are needed,
then it's a simple matter of picking position zero for the key and position one for the value.
:local keyfile [:parse [:system script get read-keyfile source]]
:local config [$keyfile "monitor-api" ":"]
:local user [:pick ($config->0) 1]
:local password [:pick ($config->1) 1]
..... More logic here.....
Create the script as read-keyfile
:local filename $1
:local delimiter $2
:local result {nil}
:local aidx 0
:local eof -1
:local eol 0
:local idx 0
:local line
:local cfgfile
:do {
	:if (($delimiter = "") || ($delimiter = nil)) do={:set $delimiter ":"}
	:if ([:file find name=$filename] != "") do={
		:set $cfgfile [:file get [:file find name=$filename] contents]
	}
	:if ([:len $cfgfile] < 1) do={
		:set $cfgfile [:file get [:file find name=($filename.".txt")] contents]
	}
	:if ([:len $cfgfile] < 1) do={:return {1,1}}
	:set $eof [:len $cfgfile]
	:do {
		:set $eol ([:find $cfgfile "\r"]);
		:if ( ($eol=0)||($eol=nil) ) do={:set $eol ([:find $cfgfile "\n"])}
		:if ( ($eol=0)||($eol=nil) ) do={:set $eol $eof}
		:set $line [:pick $cfgfile 0 $eol]
		:if ([:len $line] > 1) do={
			:set $idx [:find $line $delimiter]
			:set ($result->$aidx) {[:pick $line 0 ($idx)];[:pick $line ($idx+1) $eol]}
			:set $aidx ($aidx + 1);
		}
		:set $cfgfile [:pick $cfgfile ($eol +2) $eof]
		:set $eof ($eof - $eol);
	} while=($eol > 0)
} on-error={:log error "Could not read configuration file $filename"}
:return $result
Last edited by icosasupport on Thu Nov 23, 2017 4:26 am, edited 6 times in total.
 
icosasupport
just joined
Posts: 22
Joined: Fri Oct 13, 2017 8:37 pm

Re: Useful scripts

Wed Nov 08, 2017 7:31 pm

Hey all,

Here's a simple function that will replace a single character in a string of text with another

To call the function simply reference it in your code.
The first parameter is the string to replace a character in
Parameter 2 is the character to find
Parameter 3 is the "replacement" character
:local replace [:parse [:system script get replace-char source]]
:local hostname [$replace ([:system identity get name]) " " "-"]
Create the script as replace-char
:local match $2
:local replace $3
:local result
:for i from=0 to=([:len $1] - 1) do={ 
	:local char [:pick $1 $i]
	:if ($char = $match) do={:set $char $replace}
	:set $result ($result.$char)
}
:return $result
Last edited by icosasupport on Wed Nov 08, 2017 8:37 pm, edited 1 time in total.
 
icosasupport
just joined
Posts: 22
Joined: Fri Oct 13, 2017 8:37 pm

Re: Useful scripts

Wed Nov 08, 2017 8:05 pm

Hey all,

Here's an advanced function that will add a device to Observium http://docs.observium.org/api/#adding-a-device via the REST API call. You do however need the licensed version to use the API calls. This has not been fully tested in the latest version! (17.9.xxx) so some adjustments may have to be made, since the dev team @observium has not fully committed the API yet.

I needed to first post the support functions this script uses in order to tie it all together. (See the previous posts for the support scripts)
The monitor-api.txt sample provides the key:value pairs you'll need to call the API, please adjust them for your environment.

We're currently using it to add devices when they successfully get an IP address from the DHCP server. You can add some custom filtering if you need so that not all devices are given to the API, however that's up to you in your environment.

When calling addmonitor the first parameter is the hostname and the second parameter is the domain name suffix.
We use dynamically created DNS to resolve each device on the Observium side, if you don't have this in place then passing the IP address as the hostname should work with no domainname suffix.
We've chosen to statically set out domainname suffix in the DHCP script instead of dynamically looking it up, the choice is yours.

Create this code as the lease-script for your DHCP server, as below or copy it into the winbox script window
/ip dhcp-server
add authoritative=yes disabled=no interface=ether1 address-pool=pool1 lease-time=7d name=equipment-dhcp use-radius=no \
	lease-script="...[DHCP LEASE SCRIPT]......."
DHCP lease script to paste into WINBOX.
DHCP-LEASE-WINBOX.JPG
:local replace [:parse [:system script get replace-char source]]
:local addmonitor [:parse [:system script get add-monitor-device source]]
:local domainname "equipment.domain.local"
/ip dhcp-server lease
:if ($leaseBound = 1) do={
	:local hostname [ get [find where active-address=$leaseActIP] host-name]
	:set $hostname [$replace $hostname "." "-"]
	:if ([:len $hostname] <= 1) do={:set $hostname [$replace $leaseActMAC ":" ""]}
	:do {
		[$addmonitor $hostname $domainname]
	} on-error={:log error "Error updating API for DHCP client"}
}
Here's an idea of code to do filtering based on a simple regex. You can place it in either the DHCP lease script or in the add-monitor-device script
:if (!($hostname ~"COMPARE TO ME")) do={:return -1}
Create the script as add-monitor-device
You can change the keep variable to save the results of the API call to the router and possibly parse it to check the status. The sample code at the end is commented out, it just echoed the file to the console and log.
Note: The Observium API returns a JSON string from the API call so parsing it can be tricky with ROS scripts.
:global configfolder
:local keyfile [:parse [:system script get read-keyfile source]]
:local replace [:parse [:system script get replace-char source]]
:local convert [:parse [:system script get replace-lowup source]]
:local domainname "router.domain.local"
:local community "public"
:local hostname [$replace ([:system identity get name]) " " "-"]
:local keep true
:local apikey ($configfolder."monitor-api")
:local results ($configfolder."monitor-results.txt")
:local api
:local user
:local pass
:local url
:if (($1 != "") && ($1 != nil)) do={:set $hostname [$replace $1 " " "-"]}
:if (($2 != "") && ($2 != nil)) do={:set $domainname $2}
:do {
	:if (!($hostname ~"XXX-")) do={:return -1}
	:set $hostname [$convert $hostname 1]
}
:do {:set $api [$keyfile $apikey ":"]} on-error={:log error "Could not load API information from file $apikey"}
:do {
	:set $user [:pick ($api->0) 1]
	:set $pass [:pick ($api->1) 1]
	:set $url ([:pick ($api->2) 1].[:pick ($api->3) 1].[:pick ($api->4) 1])
} on-error={:log error "Could not parse API array"; return 0}
:do {[:file remove [:file find name=$results]]} on-error={}
:log info "Start add device $hostname.$domainname to monitor server via API [$url]"
:do {
	:local content "hostname=$hostname.$domainname&snmp_community=$community"
	#:log info $content
	[:tool fetch user=$user password=$pass url=$url keep-result=$keep http-method=post http-data=$content check-certificate=no dst-path=$results]
	:log info "Added device to monitoring server completed"
} on-error={:log warn "Warning calling monitor API to add device $hostname"; return 0}
:if ($keep) do={
	:delay 1s
	:set $results [:file get [:file find name=$results] contents]
}
:return $results
We've achieved some really complex scripting by using scripts as functions inside of other scripts. I hope this example gives you and idea of what is possible when scripts are created this way with re-usable functions.

Thanks.
Icosa
You do not have the required permissions to view the files attached to this post.
Last edited by icosasupport on Thu Nov 23, 2017 2:27 am, edited 3 times in total.
 
icosasupport
just joined
Posts: 22
Joined: Fri Oct 13, 2017 8:37 pm

Re: Useful scripts

Wed Nov 08, 2017 9:26 pm

Hey all,

Need to calculate your IP subnets but don't have access to the internet? How about as part of scripts? Maybe to create dynamic IP pools?
Here's our IP subnet calculator function. It's probably not optimized in the calculation part, but it does work so we're just using it 'as is'
We make this part of the router startup routine so that it's a global variable you can access in a terminal window without having to load parse it.
You can get results in two ways, one as text to display the calc and two as an array to use in other functions.

Sample usage from the terminal window.
Call ipcalc with 2 parameters, first is the IP subnet in CIDR format, second is the flag to display the results.
:local ipcalc [:parse [:system script get ip-calc source]]; :put [$ipcalc 192.168.10.0/24 1]
Results:
Start: 192.168.10.1 End: 192.168.10.254 Network: 192.168.10.0 Broadcast: 192.168.10.255 Subnetmask: 255.255.255.0 Usable: 254

Sample usage from a script.
Calling ipcalc without the second parameter returns and array so you can use it as a variable.
The array is structured with the same layout as you can see on the console with a starting index of zero.
:local ipcalc [:parse [:system script get ip-calc source]]; 
:local subnet [$ipcalc 192.168.10.0/24]
:log info ("Broadcast address is ".($subnet->3))
Array structure: $subnet will equal {192.168.10.1;192.168.10.254;192.168.10.0;192.168.10.255;255.255.255.0;254}

Create script as ip-calc
:local ipnetwork [:toip ([:pick $1 0 [:find $1 "/"]])]
:local cidrsubnet [:pick $1 ([:find $1 "/"] + 1) [:len $1]]
:local subnetmask  (0.0.0.0 | (255.255.255.255 << (32-$cidrsubnet)))
:local ipbroadcast ($ipnetwork | ~(255.255.255.255 << (32-$cidrsubnet)))
:local ipstart
:local ipend
:local ipusable
:set ipstart ($ipnetwork + 1) 
:set ipend (($ipnetwork | $ipbroadcast) - 1)
:local usable (~$subnetmask)
:local y 0
:local char
:local result
:while ($y < ([:len $usable] + 1)) do={
	:set char [:pick $usable $y ($y + 1)]
	:if ($char != ".") do={
		:set $result ($result.$char)
	} else={
		:set $result ($result.",")
	}
	:set $y ($y + 1)
}
:set $result [:toarray $result]
:for i from=0 to=2 do={
:set ipusable ($ipusable + ([:pick $result $i] * (256 << (8 * (2 - $i)))))
}
:set ipusable (($ipusable + [:pick $result 3]) - 1)
:if ([:len $2] != 0) do={
	:return "Start: $ipstart End: $ipend Network: $ipnetwork Broadcast: $ipbroadcast Subnetmask: $subnetmask Usable: $ipusable"
} else={
	:return [:toarray ($ipstart,$ipend,$ipnetwork,$ipbroadcast,$subnetmask,$ipusable)]
}
Please remember us or reference us when you use our scripts on your routers, we like giving back to the community as much as we can.
Thanks,
Icosa.
 
ExportHub
just joined
Posts: 1
Joined: Wed Feb 21, 2018 7:16 am
Location: Teaneck, NJ
Contact:

Re: Useful scripts

Wed Feb 21, 2018 7:18 am

All mentioned scripts are awesome. I'll try all

Thank you for sharing
 
Swordforthelord
Frequent Visitor
Frequent Visitor
Posts: 54
Joined: Thu Jul 08, 2010 10:18 pm

Re: Useful scripts

Sun Apr 08, 2018 7:19 pm

Here's a script I recently created for enabling/disabling my guest wifi. I plan to attach this script to the external mode button of a hap AC2. Please note, in the context of the script, "Guest" is the name of the wireless interface. This script checks to see if the guest wifi is disabled. If it is, it enables it and then plays two lower tones and then a high tone over the beeper. If it isn't disabled, it disables it and then plays two high tones and a low tone. This script works on my RB951G version 6.40.7. I don't know yet if it will need to be modifed for the hap AC2 as that will be my first dual-band routerboard.

{
:if ([/interface wireless get Guest disabled]=true) \
do={[/interface wireless enable Guest; /beep frequency=380 length=300ms;
:delay 300ms;
:beep frequency=380 length=300ms;
:delay 300ms;
:beep frequency=770 length=600ms;]} \
else={[/interface wireless disable Guest; beep frequency=770 length=300ms;
:delay 300ms;
:beep frequency=770 length=300ms;
:delay 300ms;
:beep frequency=380 length=600ms;]}
}
 
Swordforthelord
Frequent Visitor
Frequent Visitor
Posts: 54
Joined: Thu Jul 08, 2010 10:18 pm

Re: Useful scripts

Sun Apr 22, 2018 3:31 am

Here's a script I recently created for enabling/disabling my guest wifi. I plan to attach this script to the external mode button of a hap AC2. Please note, in the context of the script, "Guest" is the name of the wireless interface. This script checks to see if the guest wifi is disabled. If it is, it enables it and then plays two lower tones and then a high tone over the beeper. If it isn't disabled, it disables it and then plays two high tones and a low tone. This script works on my RB951G version 6.40.7. I don't know yet if it will need to be modifed for the hap AC2 as that will be my first dual-band routerboard.

{
:if ([/interface wireless get Guest disabled]=true) \
do={[/interface wireless enable Guest; /beep frequency=380 length=300ms;
:delay 300ms;
:beep frequency=380 length=300ms;
:delay 300ms;
:beep frequency=770 length=600ms;]} \
else={[/interface wireless disable Guest; beep frequency=770 length=300ms;
:delay 300ms;
:beep frequency=770 length=300ms;
:delay 300ms;
:beep frequency=380 length=600ms;]}
}
I've updated my script as it turns out the hap AC2 does not have a beeper; this new script, in addition to triggering the beeper (no harm done if your RB doesn't have one), also turns on the user-led when the guest wifi is on and turns the led off when the guest wifi is off.
{
:if ([/interface wireless get Guest disabled]=true) \
do={[/interface wireless enable Guest;
/beep frequency=380 length=300ms;
:delay 300ms;
:beep frequency=380 length=300ms;
:delay 300ms;
:beep frequency=770 length=600ms;
/system leds set [find where leds=user-led] type=on;]} \
else={[/interface wireless disable Guest;
/beep frequency=770 length=300ms;
:delay 300ms;
:beep frequency=770 length=300ms;
:delay 300ms;
:beep frequency=380 length=600ms;
/system leds set [find where leds=user-led] type=off;]}
}
Please note that for this to work, you would first need to run the command:
/system leds add leds=user-led type=off
This creates the LED setting for the command in the script to manipulate.
 
snakefox666
just joined
Posts: 1
Joined: Wed Apr 18, 2018 9:01 am

Re: Useful scripts

Wed May 09, 2018 5:15 pm

Here's a script I recently created for enabling/disabling my guest wifi. I plan to attach this script to the external mode button of a hap AC2. Please note, in the context of the script, "Guest" is the name of the wireless interface. This script checks to see if the guest wifi is disabled. If it is, it enables it and then plays two lower tones and then a high tone over the beeper. If it isn't disabled, it disables it and then plays two high tones and a low tone. This script works on my RB951G version 6.40.7. I don't know yet if it will need to be modifed for the hap AC2 as that will be my first dual-band routerboard.

{
:if ([/interface wireless get Guest disabled]=true) \
do={[/interface wireless enable Guest; /beep frequency=380 length=300ms;
:delay 300ms;
:beep frequency=380 length=300ms;
:delay 300ms;
:beep frequency=770 length=600ms;]} \
else={[/interface wireless disable Guest; beep frequency=770 length=300ms;
:delay 300ms;
:beep frequency=770 length=300ms;
:delay 300ms;
:beep frequency=380 length=600ms;]}
}
I've updated my script as it turns out the hap AC2 does not have a beeper; this new script, in addition to triggering the beeper (no harm done if your RB doesn't have one), also turns on the user-led when the guest wifi is on and turns the led off when the guest wifi is off.
{
:if ([/interface wireless get Guest disabled]=true) \
do={[/interface wireless enable Guest;
/beep frequency=380 length=300ms;
:delay 300ms;
:beep frequency=380 length=300ms;
:delay 300ms;
:beep frequency=770 length=600ms;
/system leds set [find where leds=user-led] type=on;]} \
else={[/interface wireless disable Guest;
/beep frequency=770 length=300ms;
:delay 300ms;
:beep frequency=770 length=300ms;
:delay 300ms;
:beep frequency=380 length=600ms;
/system leds set [find where leds=user-led] type=off;]}
}
Please note that for this to work, you would first need to run the command:
/system leds add leds=user-led type=off
This creates the LED setting for the command in the script to manipulate.
Hello, thanks for sharing your script ;)
I'm very interested in your script, I tried to put it in place without success but I'm using a RouterBoard hEX as CAPSMan and a cAP ac as AP. So my question is how can we trigger something from the button on the cAP ac and disable the guest wifi (for example) that is managed by the hEX :-(
Don't know if it's clear enough ...
 
vineetlogicsofts
just joined
Posts: 3
Joined: Wed Jun 13, 2018 5:13 pm
Location: Melbourne

Re: Useful scripts

Wed Jun 13, 2018 5:22 pm

Thanks, :) Janisk. I found these scripts very useful for the RouterOS version which I am using and want to discover more about this.
Web Developer in a web design company Melbourne
 
User avatar
doneware
Trainer
Trainer
Posts: 483
Joined: Mon Oct 08, 2012 8:39 pm
Location: Hungary

proper BGP peer logging

Sat Jul 14, 2018 3:05 pm

If you need cisco/juniper like bgp peer logging you might find this script handy. tested on routeros 6.42.5, but in general shall work in all v6 releases. it will generate logs with severity=info if the peer state advances from disabled towards enstablished, and it will log "errors" as it decreases, i.e. an established peer is disrupted.
you should run this from scheduler in 1m intervals.
       :global oldbgpstate
       :if (:len $oldbgpstate = 0 ) do={ :set $oldbgpstate {"_dummy"=33} }
       :local bgpstates ({disabled=0},{idle=1},{connect=2},{active=3},{opensent=4},{openconfirm=5},{established=6})
       /routing bgp peer
       :local peerstate
       :foreach peer in=[/routing bgp peer find ] do={
            :local pstate [get $peer state]
            :if ( [get $peer disabled] ) do={ :set $pstate value="disabled" }
            :local peername [get $peer name]
            :local severity "info"
       
            :if ( ($bgpstates->($oldbgpstate->$peername)) > ($bgpstates->$pstate) ) do={
                #raise error if state is decreasing
                :set $severity "error"
                }
            :if ($oldbgpstate->$peername != $pstate) do={
                #peer state changed
                :local peerip [get $peer "remote-address"]
                :local message "bgp,$severity peer $peerip ($peername) changed state to $pstate"
                :if ($severity = "error") do={
                    :log error message=$message
                } else={
                    :log info message=$message
                }
            }
            :set ($oldbgpstate->$peername) value="$pstate"
       }

#TR0359
 
User avatar
vecernik87
Long time Member
Long time Member
Posts: 642
Joined: Fri Nov 10, 2017 8:19 am

Re: Useful scripts

Thu Aug 09, 2018 5:11 am

Its nice that you wrote it but you are not controlling the page.
It is not unusual for websites to get hacked and get some hidden code included.
You may for example post the script directly here instead of some Korean page, which probably most of local users don't understand.
Also, some explanation would be great. "L4 script" is not really descriptive name and all comments in the script are in Korean as well.

The malware alert is probably due to some advertisement or other third party element which is recognized as bad.


irrelevant - can be deleted... post, which I reacted on, was deleted
Last edited by vecernik87 on Thu Nov 15, 2018 5:45 am, edited 4 times in total.
 
gabryb85
just joined
Posts: 3
Joined: Mon Apr 23, 2018 9:54 am

VPN with DDNS

Wed Sep 05, 2018 1:19 pm

Hi,
i made and tested a code for setting every 15 minutes VPN with DDNS. Sorry for Italian in comments.
#Imposta ID della VPN (ID - 1)
:global VPNID 1
# Imposta DDNS_Sorgente attualmente legato al DDNS 
:global DDNSSorgente [:resolve xxxxxxxxxxx.sn.mynetname.net]
# Imposta DDNS_Destinazione attualmente legato al DDNS
:global DDNSDestinazione [:resolve yyyyyyyyyyyyyy.sn.mynetname.net]
# Imposta VPN_Sorgente
:global VPNSorgente [/ip ipsec policy get $VPNID sa-src-address]
#Imposta VPN_Destinazione
:global VPNDestinazione [/ip ipsec policy get $VPNID sa-dst-address]

#Verifica se cambiato IP Sorgente, nel caso lo modifica nella VPN
:if ($DDNSSorgente !=$VPNSorgente)  do={
:log info "IP sorgente $VPNSorgente cambiato in $DDNSSorgente"
/ip ipsec policy set $VPNID sa-src-address=$DDNSSorgente} else= {:log info "Nessun cambiamento IP sorgente"}
:log info "Verifica IP Sorgente $DDNSSorgente con successo"

#Verifica se cambiato IP Destinazione, nel caso lo modifica nella VPN
:if ($DDNSDestinazione!=$VPNDestinazione)  do={
:log info "IP destinazione $VPNDestinazione cambiato in $DDNSDestinazione"
/ip ipsec policy set $VPNID sa-dst-address=$DDNSDestinazione} else= {:log info "Nessun cambiamento IP Destinazione"}
:log info "Verifica IP Destinazione $DDNSDestinazione eseguita con successo"
 
User avatar
astounding
Member Candidate
Member Candidate
Posts: 121
Joined: Tue Dec 16, 2008 12:17 am

Unix-style Timestamp Functions

Wed Nov 14, 2018 11:40 pm

I've need to do some date/time comparisons on RouterOS 6.40.9, and as new scripting commands to make this easier don't yet exist--see the "Built in function library" thread--I did it the hard way.

This script provides three basic timestamp functions. All three use name-based arguments, not positional.
  • getUnixTimestamp date time [offset]
  • getNow
  • getFileTimestamp filename
More documentation appears in comments in the code below:

NOTE: Updated to version 1.1 fixing a few bugs
## -----
## timestamp - a few utility functions for handling date + time timestamps as Unix-style
##             integer timestamps (seconds since the midnight Jan. 1, 1970 GMT epoch)
##
##   Version 1.1
##
##   Written by Aaron D. Gifford
##   https://www.aarongifford.com/
##
##   The above author, and original copyright owner, InfoWest, Inc. hereby place this code in the
##   PUBLIC DOMAIN.  You may use this code in any way.  You may alter it.  Redistribute it or any
##   derivitave with NO requirements whatsoever.  You may remove this notice or remove the
##   author's name.  You could even claim you wrote it (though that's not very cool).  Attribution
##   or acknowledgement is appreciated, but not required.  Have fun!  (NO WARRANTIES, etc.)
## -----

## FUNCTION:
##   getUnixTimestamp date="jan/01/1970" time="00:00:00" [offset=0]
##    * date is a string in the form "mon/DD/YYYY"
##    * time is a string in the form "HH:MM:SS" (24-hour clock)
##    * offset is an OPTIONAL signed integer number of seconds east of GMT
##      such that a positive offset is for zones east of GMT and a negative
##      offset is for zones west of GMT.  IF NOT included, the script will
##      retrieve the currently ative device offset using:
##        /system clock get gmt-offset
##
##   Example use:
##     {
##       :local timestamp [$getUnixTimestamp time=[/system clock get date] date=[/system clock get time]]
##       ...
##
##   RETURNS a Unix-style timestamp, an integer number of seconds elapsed since the Unix epoch
##   (01 JAN 1970 GMT).  Hopefully MikroTik will soon add a system funtion to return a timestamp
##   directly, making this obsolete.
##
## FUNCTION:
##   getNow
##
##   RETURNS the same thing as doing:
##     $getUnixTimestamp time=[/system clock get date] date=[/system clock get time]
##
## FUNCTION:
##   getFileTimestamp fname="filename.txt"
##    * fname - the name/path of the file for which a creation timestamp will be retrieved
##
##   RETURNS:
##     Unix-style timestamp of creation date/time for file OR returns false if file was not found
##


:global getUnixTimestamp do={
  :local timestr [:tostr $time]
  :local datestr [:tostr $date]
  :local timestamp ([:tonum [:pick $timestr 0 2]]*3600 + [:tonum [:pick $timestr 3 5]]*60 + [:tonum [:pick $timestr 6 8]])

  ## Month number, zero-based (0=January)
  :local mon ([:find "janfebmaraprmayjunjulaugsepoctnovdec" [:pick $datestr 0 3]]/3)

  ## For each month already passed, account for the days passed (ignoring Feb. 29th for now):
  :local i 0
  :while ($i < $mon) do={
    :set timestamp ([:pick {31;28;31;30;31;30;31;31;30;31;30;31} $i] * 86400 + $timestamp)
    :set i ($i+1)
  }

  ## Account for the number of days already passed for the current month:
  :set timestamp (86400*([:tonum [:pick $datestr 4 6]]-1)+$timestamp)

  :local year [:tonum [:pick $datestr 7 11]]

  ## For each year completed since the epoch, include 365 days worth of seconds (again ignoring leap years):
  :set timestamp (($year-1970)*31536000+$timestamp)

  ## Account for Feb. 29 additionl days in leap years already completed:
  :set i 1970
  :while ($i<$year) do={
    :if (($i+3)/4 = $i/4 && (($i+99)/100 != $i/100 || ($i+399)/400 = $i/400)) do={
      ## REMEMBER: Leap years occur on years evenly divisible by 4 EXCEPT for those
      ## that are ALSO evenly divisible by 100 UNLESS the century year is ALSO
      ## divisible by 400 (in which case it IS a leap year after all):
      :set timestamp (86400+$timestamp)
    }
    :set i ($i+1)
  }

  ## IF the date in question is already past February, account for a leap day IF this year is
  ## a leap year too:
  :if ($mon > 1 && ($year+3)/4 = $year/4 && (($year+99)/100 != $year/100 || ($year+399)/400 = $year/400)) do={
    :set timestamp (86400+$timestamp)
  }

  ## Account for time zone offset:
  :local tzoffset $offset
  :if ([:typeof $tzoffset] = "nothing") do={
    :set tzoffset [/system clock get gmt-offset]
  }
  :if ($tzoffset > 2147483648) do={
    ## A VERY LARGE integer indicates that the offset is negative (west). Convert
    ## the offset and subtract the resulting negative integer from the timestamp
    ## (i.e. add the positive absolute value to the timestamp):
    :set timestamp (4294967296-$tzoffset+$timestamp)
  } else={
    ## A small integer indicates the offset is positive (east).  Simply subtract
    ## it from the timestamp:
    :set timestamp ($timestamp-$tzoffset)
  }

  :return $timestamp
}


:global getNow do={
  :global getUnixTimestamp
  :return [$getUnixTimestamp date=[/system clock get date] time=[/system clock get time]]
}


:global getFileTimestamp do={
  :global getUnixTimestamp
  :local fts [/file find where name="$fname"]
  :if ([:len $fts]=0) do={
    ## No file found!
    :return false
  }
  :set fts [:tostr [/file get value-name=creation-time $fts]]
  :return [$getUnixTimestamp date=[:pick $fts 0 11] time=[:pick $fts 12 20]]
}

## The End
Enjoy!

-Astounding
 
fgonzalezm
just joined
Posts: 1
Joined: Mon Feb 11, 2019 5:31 pm

Re: Useful scripts

Mon Feb 11, 2019 5:36 pm

Hi all, i am a newbie on mikrotik, and actually use Winbox for admin the Secrets.... anyone have an script to export a TXT file with the complete data from the secrets ? ... thanks a lot
 
User avatar
hilton
Long time Member
Long time Member
Posts: 635
Joined: Thu Sep 07, 2006 5:12 pm
Location: Jozi (aka Johannesburg), South Africa

Re: Useful scripts

Wed Feb 13, 2019 10:47 am

Would this not work?
/ppp secret export file=secrets
Regards
Hilton
 
rostikk
just joined
Posts: 3
Joined: Wed Mar 06, 2019 12:17 am

Re: Useful scripts

Mon Mar 11, 2019 4:48 am

HI! I am looking for a way to get the router to act when a certain LAN client (ip address) sends a packet to a certain WAN address. The action would be a webhook. What would be the most effective way to setup something like this? Can anyone point me to the right direction, please?

Would I have to use packet sniffer and fetch?

Thank you!
 
rostikk
just joined
Posts: 3
Joined: Wed Mar 06, 2019 12:17 am

Re: Useful scripts

Wed Mar 13, 2019 3:16 pm

HI! I am looking for a way to get the router to act when a certain LAN client (ip address) sends a packet to a certain WAN address. The action would be a webhook. What would be the most effective way to setup something like this? Can anyone point me to the right direction, please?

Would I have to use packet sniffer and fetch?

Thank you!
Bump!

I guess, one way to do this is to setup a firewall rule, which would then trigger a script similar to this https://wiki.mikrotik.com/wiki/Wake_on_ ... te_Desktop

However, the script would have to run every 10 seconds... Is there another way to have the firewall rule trigger a script?
 
nostromog
Member Candidate
Member Candidate
Posts: 143
Joined: Wed Jul 18, 2018 3:39 pm

Re: Useful scripts

Wed Mar 13, 2019 6:41 pm


However, the script would have to run every 10 seconds... Is there another way to have the firewall rule trigger a script?
I don't think so. There are a few places where scripts can be triggered in response to events:
  • in /ppp profile (on-up, on-down), useful for all ppp-based interfaces (pptp, l2tp, sstp, pppoe, ovpn...)
  • in /ip dhcp-server (lease-script) when a dhcp-lease changes
  • in /ip dhcp-client (script)
  • ditto for /ipv6 dhcp-* except that the server attribute is called binding-script
  • in /tool netwatch (down-script, up-script) to fire when a host is visible
  • (...) Not sure if there are more hooks

I was missing another one for /interface wireless registration-table, to fire when either our station interface connects, or else when our AP interface gets a station connected. This would be similar to the dhcp stuff at the 802.11 L2 level.
I have also missed generic on-down/on-up for hardware interfaces, similar to ppp actions but at the /interface level.
I'd also woul like a scripted action for logs, something like /system logging add topics=health action=script where the script action would call a script with the log line...

But of course I understand the developers need to concentrate efforts, though, and keep the distribution size under control.

Who is online

Users browsing this forum: No registered users and 12 guests