0% found this document useful (0 votes)
750 views

Scripting With Mikrotik

This document discusses scripting with MikroTik routers. It provides an overview of scripting languages and why scripting is useful for tasks like automation, repetition of tasks, and monitoring routers. It then covers basic scripting commands like variables, conditional statements, and examples of basic scripts for backups, changing gateways, and deleting SMS messages. More advanced topics discussed include loops, system parameters, functions, and examples of blocking websites using a script.

Uploaded by

Naz Lun
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
750 views

Scripting With Mikrotik

This document discusses scripting with MikroTik routers. It provides an overview of scripting languages and why scripting is useful for tasks like automation, repetition of tasks, and monitoring routers. It then covers basic scripting commands like variables, conditional statements, and examples of basic scripts for backups, changing gateways, and deleting SMS messages. More advanced topics discussed include loops, system parameters, functions, and examples of blocking websites using a script.

Uploaded by

Naz Lun
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

:$cripting with MikroTik

By SOUMIL GUPTA BHAYA


Mikortik Certified Trainer
What is Scripting ?
• A scripting language is a programming language that employs a high-level
construct to interpret and execute one command at a time.

• Scripts are programs written for a special run-time environment that


automate the execution of tasks.

• They are distinct from the core code of the application.

• Often created or at least modified by the end-user.


Why Do We Need Scripting ?
• Automation of tasks based on events.

• Repetition of regular tasks.

• Batch creation and processing of lists, addresses etc.

• Monitoring of router.
Basic Scripting Commands/Syntax

• Simple • /ip address print


• /interface Ethernet set ether1 disabled=yes
Command:
• :log info “hello”;
• Syntax: • :set VariableName 10;
• :put $VariableName;

• Operators: • “+” , “-” , “=“ , “<=“ , “!=“ , “ &&” , “||” Etc.


• Arithmatic, Relational, Logical, Bitwise etc.

• global - accessible from all scripts created by current


• Variables: user. < :global Gvar >
• local - accessible only within the current scope.
< :local Lvar >
Basic Scripting Commands/Syntax:
• Variable Declaration: • Declaration of variables at start of script.
• Always keep Scope of variables in mind. (Global/Local)

• Basics: • :global Var -> Variable Declaration


• :put $Var -> Prints Value of “Var” in console
• :log info/warning/error “Hello”; -> Prints Hello in logs.
• #comments are not executed in the script.
• Conditional • :if (<condition>) do={} else={}
Statements: • Eg: :if ($a>$b) do{[:put ($a-$b)]} else={[:put ($b-$a)]}
• {} Defines Scope.
• Parentheses: • [] Command Substitution.
• () Sub Expression/Grouping.
• In the above Example, everything within the {} falls within
the scope of the do/ else commands. [] is used for command
within command. () is for grouping of arithmetic operation.
:global ddnsuser "theddnsusername"
Structuring a Script :global ddnspass "theddnspassword"
:global theinterface "interfacename"
:global ddnshost blabla.dyndns.org
:global ipddns [:resolve $ddnshost];
• Declaration of Variables :global ipfresh [ /ip address get [/ip address find interface=$theinterface ] address ]
:if ([ :typeof $ipfresh ] = nil ) do={
:log info ("DynDNS: No ip address on $theinterface .")
} else={
• Setting of Values :for i from=( [:len $ipfresh] - 1) to=0 do={
:if ( [:pick $ipfresh $i] = "/") do={
:set ipfresh [:pick $ipfresh 0 $i];
} } :if ($ipddns != $ipfresh) do={
:log info ("DynDNS: IP-DynDNS = $ipddns")
• Body :log info ("DynDNS: IP-Fresh = $ipfresh")
:log info "DynDNS: Update IP needed, Sending UPDATE...!"
:global str
"/nic/update\?hostname=$ddnshost&myip=$ipfresh&wildcard=NOCHG&mx=NOCHG&ba
ckmx=NOCHG"
/tool fetch address=members.dyndns.org src-path=$str mode=http user=$ddnsuser \
password=$ddnspass dst-path=("/DynDNS.".$ddnshost)
:delay 1
:global str [/file find name="DynDNS.$ddnshost"];
/file remove $str
:global ipddns $ipfresh
Don’t Forget Comments! :log info "DynDNS: IP updated to $ipfresh!"
} else={
:log info "DynDNS: dont need changes";
}}
Basic Scripting: Examples :put "Running System Backup
:system backup save name=RegBack;
:put "System Backed Up Successfully";
:tool e-mail send
• Regular Backup Scheduling to="[email protected]" body="test
mail" subject="$[/system identity get
name] $[/system clock get time]
• Creating Backups/Export Files $[/system clock get date] Alert"
from="[email protected]"
server="$[:resolve "smtp.gmail.com"]"
• Sending Files Via Email Tool or FTP tls=yes file=“RegBack”;
:put "System Backup Successfully E-
mailed"
• Scheduling The Script
system scheduler add name="daily
Backup" interval=24:00:00 s
tart-time=00:00:00 on-event=":system
script run stsbkp;" disabled=no
Basic Scripting: Examples
• Change Gateway to Backup
Interface
• Increasing the default route
:ip dhcp-client set 0 default-route-distance=5;
distance of DHCP Client
• Sending SMS to inform about :tool sms send port=Airtel channel=3 phone-
successful change in gateway number="9051634972" message="Gateway changed to 3g";

• Change Gateway back to


default Interface
• Decreasing the default route :ip dhcp-client set 0 default-route-distance=0;
distance of DHCP Client
:tool sms send port=Airtel channel=3 phone-
• Sending SMS to inform about number="9051634972" message="Gateway Changed to LAN";
successful change in gateway
Advanced Scripting Commands/Syntax

• Do..While -> :do {<commands>} while=(<conditions>);


• Loops: • For -> :for <var> from=<integer> to=<integer> step=<integer>
do={<commands>}
• For Each -> :foreach <var> in=<array> do={ <commands> };

• System Identity -> :global SystemIdentity [/system identity get


• System name]
Parameters: • System Clock -> :global SystemDate [/system clock get date]
• CPU Load -> :global CpuLoad [/system resource get cpu-load]

• Functions can be called in a script. Global functions can be called


in any script, thus saving excess coding.
• Functions:
• Eg:
:global myFunc do={ :return ($a + $b)}
:put [$myFunc a=6 b=2]
output->8
Advanced Scripting More Commands
• Resolve • Returns the IP address resolution for a DNS lookup.
• [:resolve xyz.com]

• Finds the first occurrence of the search term.


• Find • [:find <str> <tofind>]
• Eg: :put [/interface find name~"ether"]
• Appends data to previous file.
• Append • Eg: :tool sms inbox print append file="text log";

• Returns specific sections of provided value.


• Pick • :pick <str> <start> <end>
• :put [:pick "abcde" 1 3]
• Get selected items parameter value.
• Get • get <id> <param>=<value>
Advanced Scripting Even More
• beep • execute

• delay • environment

• len • error

• typeof • parse

• time • set
Advanced Scripting : Examples
Example of a Loop :local smscount;
• Deleting all received :set smscount [:tool sms inbox print count-only;];
:local i;
messages from inbox.
:set i 1;
:tool sms inbox print append file="text log";
:for j from=$i to=$smscount step=1 do={:tool sms
inbox print; :tool sms inbox remove numbers=0;};
:set smscount [tool sms inbox print count-only];
Advanced Scripting Another Example
• Blocking websites using :local list
DNS address :local comment
• Creating the address list. :local newip
• Creating the Firewall Rule.. :local oldip
• Picking each entry in the
“host” list. # Loop through each entry in the address list.
• Resolving the DNS given in :foreach i in=[/ip firewall address-list find] do={
the comment :set list [:pick [/ip firewall address-list get \$i list] 0 5]
• Putting the address in the # If they're 'host_', then we've got a match - process it
address list. :if (\$list = \"host_\") do={
:set comment [/ip firewall address-list get \$i comment]
/ip firewall address-list add address=0.0.0.0
comment=www.blinknet.com :set oldip [/ip firewall address-list get \$i address]
list=host_blinknet # Resolve it and set the address list entry accordingly.
/ip firewall filter add chain=forward dst- : if (\$newip != \$oldip) do={:set newip [:resolve \$comment]
address-list=host_blinknet action=drop /ip firewall address-list set \$i address=\$newip}} }
Advanced Scripting : Examples
Example of Fetching System Information
:local cpuload;
• Setting :set cpuload [system resource get cpu-load];
:local uptime;
Parameters :set uptime [system resource get uptime ];
to variables. :local version;
:set version [system resource get version ];
• Displaying in :local freemem;
:set freemem [system resource get free-memory ];
console :local freq;
and/or Logs. :set freq [system resource get cpu-frequency ];
:local sysid;
• Sending the :set sysid [system identity get name];
fetched data :put "Router Name: $sysid | Up Time: $uptime | Cpu Load: $cpuload
% | Version: $version | Free Memory: $freemem | CPU Frequency:
via SMS to $freq ";
Admin :tool sms send port=Airtel channel=3 phone-number="9051634972"
message="Router Name: $sysid | Up Time: $uptime | Cpu Load:
$cpuload % | Version: $version | Free Memory: $freemem | CPU
Frequency: $freq ";
What Can Be Achieved
• Automated system monitoring.

• Advanced Load Balancing.

• Extending Functionality.

• Easing of repetitive jobs.

• Much more, only limited by your imagination.

• A lot of resource available in the web.


Thank You for Your Attention

Questions???

You might also like