MikroTik Scripts

Setup SSH Key Login on Mikrotik

Created File and Place SSH Key Contents

Shell

Set SSH Key for Users

Shell

Setup Email Sending on Mikrotik via Postmark

Shell

Send a Test Email from Mikrotik

Shell

Backup Mikrotik Config and Email – Example 1

Shell

Backup Mikrotik Config and Email – Example 2

Shell

Setting up MikroTik/RouterOS with Conditional DNS Forwarding (UnoTelly/UnblockUS)

I have a MikroTik RouterOS device that has some custom DNS settings and therefore I cannot change the DNS servers it provides to clients, which is a requirement to use UnoTelly or Unblockus. Instead I found the following article very helpful, it allows you to configure Conditional DNS forwarding for specific domains.

https://www.dalemacartney.com/2012/12/29/dns-conditional-forwarders-with-mikrotik-routeros/

This works well because I use MediaHint to swap back and forth for NetFlix US and Canada, but use only the US Amazon Prime.

/ip firewall layer7-protocol add name=domain.com regexp=domain.com
/ip firewall mangle add chain=prerouting dst-address=<routeripaddress> layer7-protocol=domain.com action=mark-connection new-connection-mark=domain.com-forward protocol=tcp dst-port=53
/ip firewall mangle add chain=prerouting dst-address=<routeripaddress> layer7-protocol=domain.com action=mark-connection new-connection-mark=domain.com-forward protocol=udp dst-port=53
/ip firewall nat add action=dst-nat chain=dstnat connection-mark=domain.com-forward to-addresses=<UnoTellyDNSServerIPAddress>
/ip firewall nat add action=masquerade chain=srcnat connection-mark=domain.com-forward

 

MikroTik – DynDNS Update Script

This is a script for ensuring that your DynDNS hostname is updated when your IP changes on your MikroTik router. Unfortunately the script from the MikroTik Wiki doesn’t work and is broken.

http://wiki.mikrotik.com/wiki/Dynamic_DNS_Update_Script_for_dynDNS

  • There is a question mark within the URL that posts the update to members.dyndns.org and it gets removed when you paste and run the code through telnet/ssh. To fix it you will need to put a slash in-front of the question mark for it to be passed correctly.

This script is now on GitHub at https://github.com/jordantrizz/mikrotik-scripts/blob/master/dyn-dns

# Set needed variables
:local username "username"
:local password "password"
:local hostname "hostname"

:global dyndnsForce
:global previousIP 

# print some debug info
:log info ("UpdateDynDNS: username = $username")
:log info ("UpdateDynDNS: password = $password")
:log info ("UpdateDynDNS: hostname = $hostname")
:log info ("UpdateDynDNS: previousIP = $previousIP")

# get the current IP address from the internet (in case of double-nat)
/tool fetch mode=http address="checkip.dyndns.org" src-path="/" dst-path="/dyndns.checkip.html"
:local result [/file get dyndns.checkip.html contents]

# parse the current IP result
:local resultLen [:len $result]
:local startLoc [:find $result ": " -1]
:set startLoc ($startLoc + 2)
:local endLoc [:find $result "</body>" -1]
:local currentIP [:pick $result $startLoc $endLoc]
:log info "UpdateDynDNS: currentIP = $currentIP"

# Remove the # on next line to force an update every single time - useful for debugging,
# but you could end up getting blacklisted by DynDNS!

#:set dyndnsForce true

# Determine if dyndns update is needed
# more dyndns updater request details http://www.dyndns.com/developers/specs/syntax.html

:if (($currentIP != $previousIP) || ($dyndnsForce = true)) do={
   :set dyndnsForce false
   :set previousIP $currentIP
   :log info "$currentIP or $previousIP"
   /tool fetch user=$username password=$password mode=http address="members.dyndns.org" \
      src-path="/nic/update\?hostname=$hostname&myip=$currentIP&wildcard=NOCHG&mx=NOCHG&backmx=NOCHG" \
      dst-path="/dyndns.txt"
   :local result [/file get dyndns.txt contents]
   :log info ("UpdateDynDNS: Dyndns update needed")
   :log info ("UpdateDynDNS: Dyndns Update Result: ".$result)
   :put ("Dyndns Update Result: ".$result)
} else={
   :log info ("UpdateDynDNS: No dyndns update needed")
}

MikroTik – Backing Up Your MikroTik & Routerboard Config

Another great script that will email you a copy of your MikroTik/Routerboard device config. You can find the source on the MikroTik Wiki below.

http://wiki.mikrotik.com/wiki/Send_Backup_email

Some notes about the script on the MikroTik wiki and below.

  • I had to modify the script on the MikroTik website, it had used /tool e-mail set address instead of /tool e-mail set server.
  • Ensure that you specify an IP Address for sending an email, a host name will fail.

I’ve moved the code to GitHub just because its awesome and it will track changes! The latest code is available at https://github.com/jordantrizz/mikrotik-scripts/blob/master/backup

/export file=([/system identity get name] . "-" . \
[:pick [/system clock get date] 7 11] . [:pick [/system clock get date] 0 3] . [:pick [/system clock get date] 4 6]); \
/tool e-mail send to="[email protected]" subject=([/system identity get name] . " Backup " . \
[/system clock get date]) file=([/system identity get name] . "-" . [:pick [/system clock get date] 7 11] . \
[:pick [/system clock get date] 0 3] . [:pick [/system clock get date] 4 6] . ".rsc"); :delay 10; \
/file rem [/file find name=([/system identity get name] . "-" . [:pick [/system clock get date] 7 11] . \
[:pick [/system clock get date] 0 3] . [:pick [/system clock get date] 4 6] . ".rsc")]; \
:log info ("System Backup emailed at " . [/sys cl get time] . " " . [/sys cl get date])

Please note: The code above was incorrectly formatted and may have had some characters changed or stripped when it was first posted. I have since updated the above code and it should be correct, if you have any issues then post a comment. -Jordan @ 09/12/12

MikroTik – Automatically creating DNS record for each DHCP lease/client

You’ll notice that when you first get your MikroTik router, that it doesn’t create DNS records for each DHCP client that successfully receives a lease. The below article provides the necessary script to create a DNS record for each DHCP Client. I’ve provided a link to the Mikrotik Wiki article so you can see the original source.

http://wiki.mikrotik.com/wiki/Setting_static_DNS_record_for_each_DHCP_lease

The script does need to be modified (white spaces taken out) so that it will run correctly on the MikroTik. I’ve done this already and provided the script below. Also, make sure that you change :local zone “local”; to your network domain name or dns search suffix.

You will also have to create this script via telnet/ssh as webfig will mess up line 11 and remove the “\\” and leave “\”. If you don’t know how to add a script via telnet/ssh, simply type system script add name=”dhcp-dns” soruce={ at which point you can then paste the script content below. You will then have to complete the line by entering in again.

Viola! Execute the script to ensure it runs without errors system scripts run name=dhcp-dns. Lastly we want to run this script often, to ensure the records are created and updated. Lets set a schedule run system scheduler add name=dhcp-dns-run interval=5m on-event=dhcp-dns and now the script should be running every 5 minutes. To confirm the scheduler is working, wait 5 minutes and then run system scheduler print and look at the “RUN-COUNT” value, which should be greater than 0.

This script is now in GitHub and can be seen here https://github.com/jordantrizz/mikrotik-scripts/blob/master/dhcp-dns

:local zone "local";
:local ttl "00:05:00"
:local hostname
:local ip
:local dnsip
:local dhcpip
:local dnsnode
:local dhcpnode

/ip dns static;
:foreach i in=[find where name ~ (".*\\.".$zone) ] do={
  :set hostname [ get $i name ];
  :set hostname [ :pick $hostname 0 ( [ :len $hostname ] - ( [ :len $zone ] + 1 ) ) ];
  /ip dhcp-server lease;
  :set dhcpnode [ find where host-name=$hostname ];
  :if ( [ :len $dhcpnode ] > 0) do={
    :log debug ("Lease for ".$hostname." still exists. Not deleting.");
  } else={
# there's no lease by that name. Maybe this mac has a static name.
    :local found false
    /system script environment
    :foreach n in=[ find where name ~ "shost[0-9A-F]+" ] do={
       :if ( [ get $n value ] = $hostname ) do={
         :set found true;
       }
    }
    :if ( found ) do={
      :log debug ("Hostname ".$hostname." is static");
    } else={
      :log info ("Lease expired for ".$hostname.", deleting DNS entry.");
      /ip dns static remove $i;
    }
  }
}

/ip dhcp-server lease;
:foreach i in=[find] do={
  :set hostname ""
  :local mac
  :set dhcpip [ get $i address ];
  :set mac [ get $i mac-address ];
  :while ($mac ~ ":") do={
    :local pos [ :find $mac ":" ];
    :set mac ( [ :pick $mac 0 $pos ] . [ :pick $mac ($pos + 1) 999 ] );
  };
  :foreach n in=[ /system script environment find where name=("shost" . $mac) ] do={
    :set hostname [ /system script environment get $n value ];
  }
  :if ( [ :len $hostname ] = 0) do={
    :set hostname [ get $i host-name ];
  }
  :if ( [ :len $hostname ] > 0) do={
    :set hostname ( $hostname . "." . $zone );
    /ip dns static;
    :set dnsnode [ find where name=$hostname ];
    :if ( [ :len $dnsnode ] > 0 ) do={
# it exists. Is its IP the same
      :set dnsip [ get $dnsnode address ];
      :if ( $dnsip = $dhcpip ) do={
        :log debug ("DNS entry for " . $hostname . " does not need updating.");
      } else={
        :log info ("Replacing DNS entry for " . $hostname);
        /ip dns static remove $dnsnode;
        /ip dns static add name=$hostname address=$dhcpip ttl=$ttl;
      }
    } else={
# it doesn't exist. Add it
      :log info ("Adding new DNS entry for " . $hostname);
      /ip dns static add name=$hostname address=$dhcpip ttl=$ttl;
    }
  }
}

 

 

*UPDATE 10/01/2014* A much better script has been created by Tyler and is available at http://www.tolaris.com/2014/09/27/synchronising-dhcp-and-dns-on-mikrotik-routers/

Mikrotik Routerboard Pictures

Here are some pictures of the Routerboard 750G, I purchased two of them. One I will be deploying in a 22 room hotel, the other is one to play with at home.

This thing is absolutely awesome when it comes to customization, and what it can do. It does more than dd-wrt. However dd-wrt is great since you can put it on any consumer hardware.

Here are some pictures of the Routerboard 750G’s I just picked up. Awesome equipment!