├── .gitignore ├── LICENSE ├── README.md ├── ap-scripts ├── README.md ├── wifi-button.rsc ├── wifi-disable.rsc └── wifi-enable.rsc ├── default-conf-v7.6.rsc ├── doh-scripts ├── README.md ├── cloudflare-1.1.1.1.rsc ├── cloudflare-dns.rsc ├── cloudflare-one.one.one.one.rsc ├── generic.rsc ├── google.rsc ├── mullvad-family.rsc ├── nextdns.rsc └── quad9.rsc ├── scripts ├── auto-update-ros.rsc ├── backup-buttons.rsc ├── backup-cron.rsc ├── backup-leases.rsc ├── backup-scripts.rsc ├── cloud-backup.rsc ├── email-log.rsc ├── firmware-check-rb.rsc ├── firmware-check-ros-v2.rsc ├── firmware-check-ros.rsc ├── firmware-check.rsc ├── hap-ac2-bootstrap.rsc ├── init.rsc ├── ntp-client-v6.rsc ├── ntp-client-v7.rsc ├── temparature.rsc ├── toggle-tx-speed.rsc └── unknown-device.rsc ├── test-snippets ├── README.md ├── email-dns-bug.rsc ├── test-array.rsc ├── test-detect-internet-minspeed.rsc ├── test-detect-internet.rsc ├── test-empty-env-var ├── test-generate-password ├── test-log ├── test-timesync.rsc └── test-version-7.19.rsc └── tik-forum-users └── wan-monitor.rsc /.gitignore: -------------------------------------------------------------------------------- 1 | .local* 2 | *.local.rsc 3 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # MikroTik Scripts 2 | 3 | MikroTik RouterOS based Scripts, Schedules (aka cron jobs), Tips and Tricks 4 | 5 | ## In this repo... 6 | 7 | - [DoH Scripts](https://github.com/pothi/mikrotik-scripts/tree/main/doh-scripts) 8 | - [Access Point hAP Scripts](https://github.com/pothi/mikrotik-scripts/tree/main/ap-scripts) 9 | - [WiFi Enable](https://github.com/pothi/mikrotik-scripts/blob/main/ap-scripts/wifi-enable.rsc) 10 | - [WiFi Disable](https://github.com/pothi/mikrotik-scripts/blob/main/ap-scripts/wifi-disable.rsc) 11 | 12 | #### More MikroTik scripts by me... 13 | 14 | - [LTE Scripts](https://github.com/pothi/mikrotik-lte-scripts) 15 | - Coming soon (Mikrotik v7 scripts). 16 | - Coming soon (RouterOS changes from v6 to v7). 17 | 18 | # Contact 19 | 20 | You may contact me by my first name (Github username) @riseup.net, @protonmail.com, @duck.com. 21 | -------------------------------------------------------------------------------- /ap-scripts/README.md: -------------------------------------------------------------------------------- 1 | # Scripts for Access Point 2 | 3 | Scripts for MikroTik devices with access point capability such as hAP series. 4 | 5 | Current Scripts... 6 | 7 | - Enable WiFi interfaces (early in the morning or whatever the preferred time). 8 | - Disable WiFi interfaces (at night, for example) 9 | -------------------------------------------------------------------------------- /ap-scripts/wifi-button.rsc: -------------------------------------------------------------------------------- 1 | # Only for Router OS v6 2 | # Ref: https://gist.github.com/sebastian13/47e788371474d73552593b621eeacd33 3 | 4 | :log info message=("mode button was pressed"); 5 | :local i 6 | 7 | :if ( [/int wir get 0 disabled ] = true ) do={ 8 | :foreach i in= [ /int wir find ] do={ :int wir enable $i }; 9 | } else={ 10 | :foreach i in= [ /int wir find ] do={ :int wir disable $i }; 11 | } 12 | 13 | # Wifi disable 14 | # :if ( [/int wir get 0 disabled ] = true ) do={} else={ 15 | # :foreach i in= [ /int wir find ] do={ :int wir disable $i }; 16 | # } 17 | 18 | # Wifi enable 19 | # :if ( [/int wir get 0 disabled ] = true ) do={ 20 | # :foreach i in= [ /int wir find ] do={ :int wir enable $i }; 21 | # } 22 | -------------------------------------------------------------------------------- /ap-scripts/wifi-disable.rsc: -------------------------------------------------------------------------------- 1 | # Disable WiFi interfaces at night via scheduler (cron). 2 | 3 | # To avoid being locked out, make sure to run a script to enable wifi interfaces when you wake up. 4 | # Also, put the wifi-enabler script in a button of your choice. Mode button or reset button. Mode button is recommended. 5 | # See below... 6 | 7 | /system scheduler 8 | add comment="Shutdown WiFi @night to avoid electronic interference!" interval=1d name="WiFi Disable" on-event=\ 9 | "/int disable [find type~\"wifi|wlan\"]"\ 10 | policy=ftp,reboot,read,write,policy,test start-date=sep/03/2023 start-time=23:04:00 11 | 12 | # /system routerboard mode-button set enabled=yes on-event="wifi-disable" 13 | -------------------------------------------------------------------------------- /ap-scripts/wifi-enable.rsc: -------------------------------------------------------------------------------- 1 | # Enable WiFi in the morning 2 | 3 | # Version: 2.0 4 | # changelog 5 | # version: 2.0 6 | # - date: 2023-09-10 7 | # - check for wifiwave2 at first. 8 | # - improve naming scheme. 9 | 10 | # using mode button 11 | # /system routerboard mode-button set enabled=yes on-event="wifi-enable" 12 | 13 | # as a cron event 14 | # /system scheduler 15 | # add comment="Enable WiFi @morning" interval=1d name="WiFi Enable" on-event="wifi-enable" \ 16 | # policy=read,write,policy,test start-date=jan/03/2022 start-time=05:30:00 17 | 18 | # as a script to be used 19 | 20 | # Enable wifiwave2/wireless interface/s if disabled. 21 | 22 | :local allwlans 23 | :local wlan 24 | 25 | :do { 26 | :set allwlans [/int wifiwave2 print as-value] 27 | } on-error={ 28 | :log info "No wifiwave2"; 29 | 30 | :do { 31 | :set allwlans [/int wireless print as-value] 32 | } on-error={ :error "No wireless either!"; } 33 | } 34 | 35 | /interface 36 | :foreach wlan in=$allwlans do={ 37 | :local wlanName ($wlan->"name") 38 | :if ( [get $wlanName disabled] = true ) do={ 39 | enable $wlanName 40 | :log info "$wlanName: Enabled"; 41 | } else={ :log info "$wlanName: Already enabled" } 42 | } 43 | -------------------------------------------------------------------------------- /default-conf-v7.6.rsc: -------------------------------------------------------------------------------- 1 | # nov/ 5/2022 11:18:42 by RouterOS 7.6 2 | # 3 | script: #| Welcome to RouterOS! 4 | #| 1) Set a strong router password in the System > Users menu 5 | #| 2) Upgrade the software in the System > Packages menu 6 | #| 3) Enable firewall on untrusted networks 7 | #| 4) Set your country name to observe wireless regulations 8 | #| ----------------------------------------------------------------------------- 9 | #| RouterMode: 10 | #| * WAN port is protected by firewall and enabled DHCP client 11 | #| * Wireless and Ethernet interfaces (except WAN port/s) 12 | #| are part of LAN bridge 13 | #| LAN Configuration: 14 | #| IP address 192.168.88.1/24 is set on bridge (LAN port) 15 | #| DHCP Server: enabled; 16 | #| DNS: enabled; 17 | #| wifi1 Configuration: 18 | #| mode: ap; 19 | #| band: 5ghz-ax; 20 | #| tx-chains: 0;1; 21 | #| rx-chains: 0;1; 22 | #| installation: indoor; 23 | #| ht-extension: 20/40/80mhz; 24 | #| wpa2: no; 25 | #| wifi2 Configuration: 26 | #| mode: ap; 27 | #| band: 2ghz-ax; 28 | #| tx-chains: 0;1; 29 | #| rx-chains: 0;1; 30 | #| installation: indoor; 31 | #| ht-extension: 20/40mhz; 32 | #| wpa2: no; 33 | #| WAN (gateway) Configuration: 34 | #| gateway: ether1 ; 35 | #| ip4 firewall: enabled; 36 | #| ip6 firewall: enabled; 37 | #| NAT: enabled; 38 | #| DHCP Client: enabled; 39 | #| Login 40 | #| admin user protected by password 41 | 42 | :global ssid; 43 | :global defconfMode; 44 | :log info "Starting defconf script"; 45 | #------------------------------------------------------------------------------- 46 | # Apply configuration. 47 | # these commands are executed after installation or configuration reset 48 | #------------------------------------------------------------------------------- 49 | :if ($action = "apply") do={ 50 | # wait for interfaces 51 | :local count 0; 52 | :while ([/interface ethernet find] = "") do={ 53 | :if ($count = 30) do={ 54 | :log warning "DefConf: Unable to find ethernet interfaces"; 55 | /quit; 56 | } 57 | :delay 1s; :set count ($count +1); 58 | }; 59 | :local count 0; 60 | :while ([/interface wifiwave2 print count-only] < 2) do={ 61 | :set count ($count +1); 62 | :if ($count = 40) do={ 63 | :log warning "DefConf: Unable to find wireless interface(s)"; 64 | /ip address add address=192.168.88.1/24 interface=ether1 comment="defconf"; 65 | /quit 66 | } 67 | :delay 1s; 68 | }; 69 | /interface list add name=WAN comment="defconf" 70 | /interface list add name=LAN comment="defconf" 71 | /interface bridge 72 | add name=bridge disabled=no auto-mac=yes protocol-mode=rstp comment=defconf; 73 | :local bMACIsSet 0; 74 | :foreach k in=[/interface find where !(slave=yes || name="ether1" || passthrough=yes || name="ether1" || name~"bridge")] do={ 75 | :local tmpPortName [/interface get $k name]; 76 | :if ($bMACIsSet = 0) do={ 77 | :if ([/interface get $k type] = "ether") do={ 78 | /interface bridge set "bridge" auto-mac=no admin-mac=[/interface get $tmpPortName mac-address]; 79 | :set bMACIsSet 1; 80 | } 81 | } 82 | :if (([/interface get $k type] != "ppp-out") && ([/interface get $k type] != "lte")) do={ 83 | /interface bridge port 84 | add bridge=bridge interface=$tmpPortName comment=defconf; 85 | } 86 | } 87 | /ip pool add name="default-dhcp" ranges=192.168.88.10-192.168.88.254; 88 | /ip dhcp-server 89 | add name=defconf address-pool="default-dhcp" interface=bridge lease-time=10m disabled=no; 90 | /ip dhcp-server network 91 | add address=192.168.88.0/24 gateway=192.168.88.1 dns-server=192.168.88.1 comment="defconf"; 92 | /ip address add address=192.168.88.1/24 interface=bridge comment="defconf"; 93 | /ip dns { 94 | set allow-remote-requests=yes 95 | static add name=router.lan address=192.168.88.1 comment=defconf 96 | } 97 | 98 | /interface wifiwave2 { 99 | :local ifcId [/interface wifiwave2 find where default-name=wifi1] 100 | set $ifcId configuration.mode=ap channel.band=5ghz-ax disabled=no 101 | set $ifcId channel.width=20/40/80mhz; 102 | set $ifcId channel.skip-dfs-channels=10min-cac; 103 | :local wlanMac [/interface get [/interface find where default-name=wifi1] mac-address]; 104 | :set ssid "MikroTik-$[:pick $wlanMac 9 11]$[:pick $wlanMac 12 14]$[:pick $wlanMac 15 17]" 105 | set $ifcId configuration.ssid=$ssid 106 | } 107 | /interface wifiwave2 { 108 | :local ifcId [/interface wifiwave2 find where default-name=wifi2] 109 | set $ifcId configuration.mode=ap channel.band=2ghz-ax disabled=no 110 | set $ifcId channel.width=20/40mhz; 111 | set $ifcId channel.skip-dfs-channels=10min-cac; 112 | :local wlanMac [/interface get [/interface find where default-name=wifi2] mac-address]; 113 | :set ssid "MikroTik-$[:pick $wlanMac 9 11]$[:pick $wlanMac 12 14]$[:pick $wlanMac 15 17]" 114 | set $ifcId configuration.ssid=$ssid 115 | } 116 | /ip dhcp-client add interface=ether1 disabled=no comment="defconf"; 117 | /interface list member add list=LAN interface=bridge comment="defconf" 118 | /interface list member add list=WAN interface=ether1 comment="defconf" 119 | /ip firewall nat add chain=srcnat out-interface-list=WAN ipsec-policy=out,none action=masquerade comment="defconf: masquerade" 120 | /ip firewall { 121 | filter add chain=input action=accept connection-state=established,related,untracked comment="defconf: accept established,related,untracked" 122 | filter add chain=input action=drop connection-state=invalid comment="defconf: drop invalid" 123 | filter add chain=input action=accept protocol=icmp comment="defconf: accept ICMP" 124 | filter add chain=input action=accept dst-address=127.0.0.1 comment="defconf: accept to local loopback (for CAPsMAN)" 125 | filter add chain=input action=drop in-interface-list=!LAN comment="defconf: drop all not coming from LAN" 126 | filter add chain=forward action=accept ipsec-policy=in,ipsec comment="defconf: accept in ipsec policy" 127 | filter add chain=forward action=accept ipsec-policy=out,ipsec comment="defconf: accept out ipsec policy" 128 | filter add chain=forward action=fasttrack-connection connection-state=established,related comment="defconf: fasttrack" 129 | filter add chain=forward action=accept connection-state=established,related,untracked comment="defconf: accept established,related, untracked" 130 | filter add chain=forward action=drop connection-state=invalid comment="defconf: drop invalid" 131 | filter add chain=forward action=drop connection-state=new connection-nat-state=!dstnat in-interface-list=WAN comment="defconf: drop all from WAN not DSTNATed" 132 | } 133 | /ipv6 firewall { 134 | address-list add list=bad_ipv6 address=::/128 comment="defconf: unspecified address" 135 | address-list add list=bad_ipv6 address=::1 comment="defconf: lo" 136 | address-list add list=bad_ipv6 address=fec0::/10 comment="defconf: site-local" 137 | address-list add list=bad_ipv6 address=::ffff:0:0/96 comment="defconf: ipv4-mapped" 138 | address-list add list=bad_ipv6 address=::/96 comment="defconf: ipv4 compat" 139 | address-list add list=bad_ipv6 address=100::/64 comment="defconf: discard only " 140 | address-list add list=bad_ipv6 address=2001:db8::/32 comment="defconf: documentation" 141 | address-list add list=bad_ipv6 address=2001:10::/28 comment="defconf: ORCHID" 142 | address-list add list=bad_ipv6 address=3ffe::/16 comment="defconf: 6bone" 143 | filter add chain=input action=accept connection-state=established,related,untracked comment="defconf: accept established,related,untracked" 144 | filter add chain=input action=drop connection-state=invalid comment="defconf: drop invalid" 145 | filter add chain=input action=accept protocol=icmpv6 comment="defconf: accept ICMPv6" 146 | filter add chain=input action=accept protocol=udp port=33434-33534 comment="defconf: accept UDP traceroute" 147 | filter add chain=input action=accept protocol=udp dst-port=546 src-address=fe80::/10 comment="defconf: accept DHCPv6-Client prefix delegation." 148 | filter add chain=input action=accept protocol=udp dst-port=500,4500 comment="defconf: accept IKE" 149 | filter add chain=input action=accept protocol=ipsec-ah comment="defconf: accept ipsec AH" 150 | filter add chain=input action=accept protocol=ipsec-esp comment="defconf: accept ipsec ESP" 151 | filter add chain=input action=accept ipsec-policy=in,ipsec comment="defconf: accept all that matches ipsec policy" 152 | filter add chain=input action=drop in-interface-list=!LAN comment="defconf: drop everything else not coming from LAN" 153 | filter add chain=forward action=accept connection-state=established,related,untracked comment="defconf: accept established,related,untracked" 154 | filter add chain=forward action=drop connection-state=invalid comment="defconf: drop invalid" 155 | filter add chain=forward action=drop src-address-list=bad_ipv6 comment="defconf: drop packets with bad src ipv6" 156 | filter add chain=forward action=drop dst-address-list=bad_ipv6 comment="defconf: drop packets with bad dst ipv6" 157 | filter add chain=forward action=drop protocol=icmpv6 hop-limit=equal:1 comment="defconf: rfc4890 drop hop-limit=1" 158 | filter add chain=forward action=accept protocol=icmpv6 comment="defconf: accept ICMPv6" 159 | filter add chain=forward action=accept protocol=139 comment="defconf: accept HIP" 160 | filter add chain=forward action=accept protocol=udp dst-port=500,4500 comment="defconf: accept IKE" 161 | filter add chain=forward action=accept protocol=ipsec-ah comment="defconf: accept ipsec AH" 162 | filter add chain=forward action=accept protocol=ipsec-esp comment="defconf: accept ipsec ESP" 163 | filter add chain=forward action=accept ipsec-policy=in,ipsec comment="defconf: accept all that matches ipsec policy" 164 | filter add chain=forward action=drop in-interface-list=!LAN comment="defconf: drop everything else not coming from LAN" 165 | } 166 | /ip neighbor discovery-settings set discover-interface-list=LAN 167 | /tool mac-server set allowed-interface-list=LAN 168 | /tool mac-server mac-winbox set allowed-interface-list=LAN 169 | :if (!($defconfPassword = "" || $defconfPassword = nil)) do={ 170 | /user set admin password=$defconfPassword 171 | :delay 0.5 172 | /user expire-password admin 173 | } 174 | } 175 | #------------------------------------------------------------------------------- 176 | # Revert configuration. 177 | # these commands are executed if user requests to remove default configuration 178 | #------------------------------------------------------------------------------- 179 | :if ($action = "revert") do={ 180 | /user set admin password="" 181 | /system routerboard mode-button set enabled=no 182 | /system routerboard mode-button set on-event="" 183 | /system script remove [find comment~"defconf"] 184 | /ip firewall filter remove [find comment~"defconf"] 185 | /ipv6 firewall filter remove [find comment~"defconf"] 186 | /ipv6 firewall address-list remove [find comment~"defconf"] 187 | /ip firewall nat remove [find comment~"defconf"] 188 | /interface list member remove [find comment~"defconf"] 189 | /interface detect-internet set detect-interface-list=none 190 | /interface detect-internet set lan-interface-list=none 191 | /interface detect-internet set wan-interface-list=none 192 | /interface detect-internet set internet-interface-list=none 193 | /interface list remove [find comment~"defconf"] 194 | /tool mac-server set allowed-interface-list=all 195 | /tool mac-server mac-winbox set allowed-interface-list=all 196 | /ip neighbor discovery-settings set discover-interface-list=!dynamic 197 | :local o [/ip dhcp-server network find comment="defconf"] 198 | :if ([:len $o] != 0) do={ /ip dhcp-server network remove $o } 199 | :local o [/ip dhcp-server find name="defconf" !disabled] 200 | :if ([:len $o] != 0) do={ /ip dhcp-server remove $o } 201 | /ip pool { 202 | :local o [find name="default-dhcp" ranges=192.168.88.10-192.168.88.254] 203 | :if ([:len $o] != 0) do={ remove $o } 204 | } 205 | :local o [/ip dhcp-client find comment="defconf"] 206 | :if ([:len $o] != 0) do={ /ip dhcp-client remove $o } 207 | /ip dns { 208 | set allow-remote-requests=no 209 | :local o [static find comment="defconf"] 210 | :if ([:len $o] != 0) do={ static remove $o } 211 | } 212 | /ip address { 213 | :local o [find comment="defconf"] 214 | :if ([:len $o] != 0) do={ remove $o } 215 | } 216 | :foreach iface in=[/interface ethernet find] do={ 217 | /interface ethernet set $iface name=[get $iface default-name] 218 | } 219 | /interface bridge port remove [find comment="defconf"] 220 | /interface bridge remove [find comment="defconf"] 221 | /interface bonding remove [find comment="defconf"] 222 | /interface wifiwave2 reset wifi1 223 | /interface wifiwave2 reset wifi2 224 | } 225 | :log info Defconf_script_finished; 226 | :set defconfMode; 227 | :set ssid; 228 | 229 | caps-mode-script: #------------------------------------------------------------------------------- 230 | # Note: script will not execute at all (will throw a syntax error) if 231 | # dhcp or wireless-fp packages are not installed 232 | #------------------------------------------------------------------------------- 233 | 234 | #| CAP configuration 235 | #| 236 | #| Wireless interfaces are set to be managed by CAPsMAN. 237 | #| All ethernet interfaces and CAPsMAN managed interfaces are bridged. 238 | #| DHCP client is set on bridge interface. 239 | 240 | # bridge port name 241 | :global brName "bridgeLocal"; 242 | :global logPref "defconf:"; 243 | 244 | 245 | :global action; 246 | 247 | :log info $action 248 | 249 | :if ($action = "apply") do={ 250 | 251 | # wait for ethernet interfaces 252 | :local count 0; 253 | :while ([/interface ethernet find] = "") do={ 254 | :if ($count = 30) do={ 255 | :log warning "DefConf: Unable to find ethernet interfaces"; 256 | /quit; 257 | } 258 | :delay 1s; :set count ($count + 1); 259 | } 260 | 261 | :local macSet 0; 262 | :local tmpMac ""; 263 | 264 | :foreach k in=[/interface ethernet find] do={ 265 | # first ethernet is found; add bridge and set mac address of the ethernet port 266 | :if ($macSet = 0) do={ 267 | :set tmpMac [/interface ethernet get $k mac-address]; 268 | /interface bridge add name=$brName auto-mac=no admin-mac=$tmpMac comment="defconf"; 269 | :set macSet 1; 270 | } 271 | # add bridge ports 272 | /interface bridge port add bridge=$brName interface=$k comment="defconf" 273 | } 274 | 275 | # try to add dhcp client on bridge interface (may fail if already exist) 276 | :do { 277 | /ip dhcp-client add interface=$brName disabled=no comment="defconf" 278 | } on-error={ :log warning "$logPref unable to add dhcp client";} 279 | 280 | 281 | # try to configure caps (may fail if for example specified interfaces are missing) 282 | :local interfacesList ""; 283 | :local bFirst 1; 284 | 285 | # wait for wireless interfaces 286 | :while ([/interface wireless find] = "") do={ 287 | :if ($count = 30) do={ 288 | :log warning "DefConf: Unable to find wireless interfaces"; 289 | /quit; 290 | } 291 | :delay 1s; :set count ($count + 1); 292 | } 293 | 294 | # delay just to make sure that all wireless interfaces are loaded 295 | :delay 5s; 296 | :foreach i in=[/interface wireless find] do={ 297 | if ($bFirst = 1) do={ 298 | :set interfacesList [/interface wireless get $i name]; 299 | :set bFirst 0; 300 | } else={ 301 | :set interfacesList "$interfacesList,$[/interface wireless get $i name]"; 302 | } 303 | } 304 | :do { 305 | /interface wireless cap 306 | set enabled=yes interfaces=$interfacesList discovery-interfaces=$brName bridge=$brName 307 | } on-error={ :log warning "$logPref unable to configure caps";} 308 | 309 | } 310 | 311 | :if ($action = "revert") do={ 312 | :do { 313 | /interface wireless cap 314 | set enabled=no interfaces="" discovery-interfaces="" bridge=none 315 | } on-error={ :log warning "$logPref unable to unset caps";} 316 | 317 | :local o [/ip dhcp-client find comment="defconf"] 318 | :if ([:len $o] != 0) do={ /ip dhcp-client remove $o } 319 | 320 | /interface bridge port remove [find comment="defconf"] 321 | /interface bridge remove [find comment="defconf"] 322 | 323 | } 324 | custom-script: 325 | -------------------------------------------------------------------------------- /doh-scripts/README.md: -------------------------------------------------------------------------------- 1 | The following DoH services can be automated for now... 2 | 3 | - [Cloudflare](https://github.com/pothi/mikrotik-scripts/blob/main/doh-scripts/cloudflare.rsc) 4 | - [Google](https://github.com/pothi/mikrotik-scripts/blob/main/doh-scripts/google.rsc) 5 | - [NextDNS](https://github.com/pothi/mikrotik-scripts/blob/main/doh-scripts/nextdns.rsc) 6 | 7 | Incompatible / buggy implementation... 8 | 9 | - [Quad9](https://github.com/pothi/mikrotik-scripts/blob/main/doh-scripts/quad9.rsc) 10 | 11 | Since Router OS v7.19... built-in CA certificates can be used with `/certificate/settings/set builtin-trust-anchors=trusted` 12 | 13 | Or you may use the [generic script](https://github.com/pothi/mikrotik-scripts/blob/main/doh-scripts/generic.rsc). 14 | 15 | Officially incompatible DoH servers... https://help.mikrotik.com/docs/spaces/ROS/pages/37748767/DNS#DNS-Knowncompatible/incompatibleDoHservices 16 | 17 | Relevant thread in MikroTik forums... https://forum.mikrotik.com/viewtopic.php?f=2&t=160243#p799274 18 | 19 | Remember that DoH depends on the correct time on your MikroTik device. So, make sure that the NTP client is configured and is working. The MikroTik's Cloud NTP client service requires a working DNS that in turn requires a working NTP client. So, please don't depend on MikroTik's Cloud NTP sync service. 20 | 21 | Root CA certificates that we can use... 22 | 23 | - https://www.digicert.com/kb/digicert-root-certificates.htm (Download DigiCert Global Root CA) 24 | - https://cacerts.digicert.com/DigiCertGlobalRootCA.crt.pem 25 | - works **only** for 1.1.1.1 DoH 26 | 27 | The following don't work for unknown reason... 28 | 29 | - https://pki.goog/repository/ 30 | - https://support.globalsign.com/ca-certificates/root-certificates/globalsign-root-certificates 31 | - https://www.amazontrust.com/repository/ 32 | 33 | Or download most (if not all) root CA certificates from https://curl.se/ca/cacert.pem 34 | 35 | Recommended - https://pki.goog/repo/certs/gtsr4.pem (validity: 2038) 36 | 37 | NextDNS recommends https://curl.se/ca/cacert.pem too. 38 | 39 | -------------------------------------------------------------------------------- /doh-scripts/cloudflare-1.1.1.1.rsc: -------------------------------------------------------------------------------- 1 | # Verify the connection at https://1.1.1.1/help 2 | 3 | # disable doh (temporarily) 4 | 5 | /ip dns set verify-doh-cert=no 6 | 7 | # update the caCertURL depending on what's used at https://1.1.1.1/dns-query 8 | 9 | :local caCertURL 10 | :set caCertURL https://cacerts.digicert.com/DigiCertGlobalRootG2.crt.pem 11 | 12 | :local result [ /tool fetch url=$caCertURL dst-path=root-ca-cert.pem as-value ]; 13 | :do { :delay 2s } while=( $result->"status" != "finished" ) 14 | 15 | /certificate remove [find name~"root-ca-cert.pem"] 16 | /certificate import file-name=root-ca-cert.pem passphrase="" 17 | /file remove root-ca-cert.pem 18 | 19 | /ip dns set use-doh-server=https://1.1.1.1/dns-query verify-doh-cert=yes 20 | 21 | # optional steps 22 | /ip dns set servers="1.1.1.1,1.0.0.1" 23 | /ip dhcp-client set use-peer-dns=no [find] 24 | 25 | # flush existing cache 26 | /ip dns cache flush 27 | -------------------------------------------------------------------------------- /doh-scripts/cloudflare-dns.rsc: -------------------------------------------------------------------------------- 1 | # Verify the connection at https://1.1.1.1/help 2 | 3 | # cloudflare-dns.com is the default DNS server (at least as of May 2025), in place of (still working) 1.1.1.1 and one.one.one.one. 4 | 5 | # disable doh (temporarily) 6 | 7 | /ip dns set verify-doh-cert=no 8 | 9 | # update the caCertURL depending on what's used at https://1.1.1.1/dns-query 10 | 11 | :local caCertURL https://cacerts.digicert.com/DigiCertGlobalRootG2.crt.pem 12 | 13 | :local result [ /tool fetch url=$caCertURL dst-path=cert.pem as-value ]; 14 | :do { :delay 2s } while=( $result->"status" != "finished" ) 15 | 16 | /certificate remove [find name~"cert.pem"] 17 | /certificate import file-name=cert.pem passphrase="" 18 | # no longer needed for RouterOS v7 19 | # /file remove cert.pem 20 | 21 | # since RouterOS v7.19... 22 | # /certificate/settings/set builtin-trust-anchors=trusted 23 | 24 | # Add static DNS entries for the DoH server 25 | /ip dns static remove [find name=cloudflare-dns.com] 26 | # use the following two entries if IPv6 is available on your internet 27 | # /ip dns static add address=2606:4700::6810:f8f9 name=cloudflare-dns.com comment="DoH" 28 | # /ip dns static add address=2606:4700::6810:f9f9 name=cloudflare-dns.com comment="DoH" 29 | /ip dns static add address=104.16.248.249 name=cloudflare-dns.com comment="DoH" 30 | /ip dns static add address=104.16.249.249 name=cloudflare-dns.com comment="DoH" 31 | 32 | /ip dns set use-doh-server=https://cloudflare-dns.com/dns-query verify-doh-cert=yes 33 | 34 | # optional steps 35 | # use the following if IPv6 is available on your internet 36 | # /ip dns set servers="2606:4700:4700::1111,2606:4700:4700::1001,1.1.1.1,1.0.0.1" 37 | /ip dns set servers="1.1.1.1,1.0.0.1" 38 | /ip dhcp-client set use-peer-dns=no [find] 39 | 40 | # flush existing cache 41 | /ip dns cache flush 42 | -------------------------------------------------------------------------------- /doh-scripts/cloudflare-one.one.one.one.rsc: -------------------------------------------------------------------------------- 1 | # Verify the connection at https://1.1.1.1/help 2 | 3 | # disable doh (temporarily) 4 | 5 | /ip dns set verify-doh-cert=no 6 | 7 | # update the caCertURL depending on what's used at https://1.1.1.1/dns-query 8 | 9 | :local caCertURL https://cacerts.digicert.com/DigiCertGlobalRootG2.crt.pem 10 | 11 | :local result [ /tool fetch url=$caCertURL dst-path=cert.pem as-value ]; 12 | :do { :delay 2s } while=( $result->"status" != "finished" ) 13 | 14 | /certificate remove [find name~"cert.pem"] 15 | /certificate import file-name=cert.pem passphrase="" 16 | # no longer needed for RouterOS v7 17 | # /file remove cert.pem 18 | 19 | # Add static DNS entries for the DoH server 20 | /ip dns static remove [find name=one.one.one.one] 21 | # use the following two entries only if IPv6 is available on your internet 22 | # /ip dns static add address=2606:4700:4700::1111 name=one.one.one.one 23 | # /ip dns static add address=2606:4700:4700::1001 name=one.one.one.one 24 | /ip dns static add address=1.1.1.1 name=one.one.one.one 25 | /ip dns static add address=1.0.0.1 name=one.one.one.one 26 | 27 | /ip dns set use-doh-server=https://one.one.one.one/dns-query verify-doh-cert=yes 28 | 29 | # optional steps 30 | # use the following only if IPv6 is available on your internet 31 | # /ip dns set servers="2606:4700:4700::1111,2606:4700:4700::1001,1.1.1.1,1.0.0.1" 32 | /ip dns set servers="1.1.1.1,1.0.0.1" 33 | /ip dhcp-client set use-peer-dns=no [find] 34 | 35 | # flush existing cache 36 | /ip dns cache flush 37 | -------------------------------------------------------------------------------- /doh-scripts/generic.rsc: -------------------------------------------------------------------------------- 1 | # Generic DoH script 2 | 3 | # disable doh (temporarily) 4 | /ip dns set verify-doh-cert=no 5 | 6 | # curl.haxx.se/ca/cacert.pem contains all the certificates in the world - 100+ 7 | :local result [ /tool fetch url=https://curl.haxx.se/ca/cacert.pem as-value ]; 8 | :do { :delay 2s } while=( $result->"status" != "finished" ) 9 | 10 | /certificate remove [find name~"cacert.pem"] 11 | /certificate import file-name=cacert.pem passphrase="" 12 | /file remove cacert.pem 13 | 14 | # you may use any DoH server 15 | # https://dns.google/dns-query - see https://forum.mikrotik.com/viewtopic.php?f=2&t=160243#p787666 16 | # https://dns.nextdns.io/xxxxxx - see https://my.nextdns.io/setup 17 | # https://dns.quad9.net/dns-query - see https://www.quad9.net/news/blog/doh-with-quad9-dns-servers/ 18 | 19 | # let's use Cloudflare DoH 20 | /ip dns set use-doh-server=https://1.1.1.1/dns-query verify-doh-cert=yes 21 | 22 | # optional steps 23 | /ip dns set servers="" 24 | /ip dhcp-client set use-peer-dns=no [find] 25 | 26 | # flush existing cache 27 | /ip dns cache flush 28 | 29 | # remove this file manually 30 | # /file remove generic.rsc 31 | -------------------------------------------------------------------------------- /doh-scripts/google.rsc: -------------------------------------------------------------------------------- 1 | # Verify the connection at TODO 2 | 3 | # disable doh (temporarily) 4 | /ip dns set verify-doh-cert=no 5 | 6 | :local result [/tool fetch url=https://i.pki.goog/r4.pem as-value] 7 | :do { :delay 2s } while=( $result->"status" != "finished" ) 8 | 9 | /certificate remove [find name~"r4.pem"] 10 | /certificate import file-name=r4.pem passphrase="" 11 | # /file remove r4.pem 12 | 13 | # Add static DNS entries for the DoH server 14 | /ip dns static remove [find name=dns.google] 15 | /ip dns static add address=8.8.8.8 name=dns.google 16 | /ip dns static add address=8.8.4.4 name=dns.google 17 | 18 | # let's enable DoH 19 | /ip dns set use-doh-server=https://dns.google/dns-query verify-doh-cert=yes 20 | 21 | # optional steps 22 | # /ip dns set servers="" 23 | # /ip dhcp-client set use-peer-dns=no [find] 24 | 25 | # flush existing cache 26 | /ip dns cache flush 27 | 28 | # remove this file manually 29 | # /file remove google.rsc 30 | -------------------------------------------------------------------------------- /doh-scripts/mullvad-family.rsc: -------------------------------------------------------------------------------- 1 | # Mullvad requires HTTP2 that is not supported by MikroTik, yet! 2 | 3 | 4 | 5 | 6 | # TODO: Verify the connection if possible 7 | # Ref: https://mullvad.net/en/help/dns-over-https-and-dns-over-tls 8 | 9 | # disable doh (temporarily) 10 | 11 | /ip dns set verify-doh-cert=no 12 | 13 | # Mullvad uses LetsEncrypt certs that in turn uses ISRG Root X1 as of Nov 2024 14 | :local result [ /tool fetch url=https://letsencrypt.org/certs/isrgrootx1.pem dst-path=mullvad-x1.pem as-value ]; 15 | :do { :delay 2s } while=( $result->"status" != "finished" ) 16 | # Let's prepare for the transition (to ISRG Root X2), though; ref: https://letsencrypt.org/certificates/ 17 | :local result [ /tool fetch url=https://letsencrypt.org/certs/isrg-root-x2.pem dst-path=mullvad-x2.pem as-value ]; 18 | :do { :delay 2s } while=( $result->"status" != "finished" ) 19 | 20 | /certificate remove [find name~"mullvad-x1.pem"] 21 | /certificate remove [find name~"mullvad-x2.pem"] 22 | /certificate import file-name=mullvad-x1.pem passphrase="" 23 | /certificate import file-name=mullvad-x2.pem passphrase="" 24 | /file remove mullvad-x1.pem 25 | /file remove mullvad-x2.pem 26 | 27 | /ip dns 28 | static remove [find name="family.dns.mullvad.net"] 29 | static add name=family.dns.mullvad.net address=194.242.2.6 comment="mullvad IPv4" 30 | # static add name=family.dns.mullvad.net address=149.112.112.112 comment="mullvad IPv4 - secondary" 31 | static add name=family.dns.mullvad.net address=2a07:e340::6 comment="mullvad IPv6" 32 | # static add name=family.dns.mullvad.net address=2620:fe::fe comment="mullvad IPv6 - secondary" 33 | 34 | set use-doh-server=https://family.dns.mullvad.net/dns-query verify-doh-cert=yes 35 | 36 | # optional steps 37 | /ip dns set servers="2a07:e340::6,194.242.2.6" 38 | /ip dhcp-client set use-peer-dns=no [find] 39 | 40 | # flush existing cache 41 | /ip dns cache flush 42 | 43 | # Post-install step: remove this file manually 44 | # /file remove mullvad.rsc 45 | -------------------------------------------------------------------------------- /doh-scripts/nextdns.rsc: -------------------------------------------------------------------------------- 1 | # TODO: Verify the connection if possible 2 | # https://dns.nextdns.io/xxxxxx - see https://my.nextdns.io/setup 3 | 4 | # Variables 5 | :local nextdnsID 6 | :local deviceName 7 | :set nextdnsID "abc123" 8 | # Avoid spaces or use unicode 9 | :set deviceName "MikroTik-AX2" 10 | 11 | # disable doh (temporarily) 12 | /ip dns set verify-doh-cert=no 13 | 14 | # NextDNS uses UserTrust ECC cert 15 | :local result [ /tool fetch url=http://crt.usertrust.com/USERTrustECCAddTrustCA.crt dst-path=nextdns.pem as-value ]; 16 | :do { :delay 2s } while=( $result->"status" != "finished" ) 17 | 18 | /certificate remove [find name~"nextdns"] 19 | /certificate import file-name=nextdns.pem passphrase="" 20 | /file remove nextdns.pem 21 | 22 | /ip dns 23 | static remove [find name="dns.nextdns.io"] 24 | static add name=dns.nextdns.io address=45.90.28.0 type=A 25 | static add name=dns.nextdns.io address=45.90.30.0 type=A 26 | static add name=dns.nextdns.io address=2a07:a8c0:: type=AAAA 27 | static add name=dns.nextdns.io address=2a07:a8c1:: type=AAAA 28 | 29 | # Configure Device Name with NextDNS, if exists. 30 | :if ( $deviceName == "" ) do={ 31 | set use-doh-server="https://dns.nextdns.io/$nextdnsID" verify-doh-cert=yes 32 | } else={ 33 | set use-doh-server="https://dns.nextdns.io/$nextdnsID/$deviceName" verify-doh-cert=yes 34 | } 35 | 36 | # optional steps 37 | # /ip dns set servers="" 38 | # /ip dhcp-client set use-peer-dns=no [find] 39 | 40 | # flush existing cache 41 | /ip dns cache flush 42 | 43 | # Post-install step: remove this file manually 44 | # /file remove nextdns.rsc 45 | -------------------------------------------------------------------------------- /doh-scripts/quad9.rsc: -------------------------------------------------------------------------------- 1 | # TODO: Verify the connection if possible 2 | # Ref: https://www.quad9.net/news/blog/doh-with-quad9-dns-servers/ 3 | 4 | # disable doh (temporarily) 5 | 6 | /ip dns set verify-doh-cert=no 7 | 8 | # Quad9 uses DigiCert like CloudFlare. 9 | :local result [ /tool fetch url=https://cacerts.digicert.com/DigiCertGlobalRootCA.crt.pem dst-path=quad9.pem as-value ]; 10 | :do { :delay 2s } while=( $result->"status" != "finished" ) 11 | 12 | /certificate remove [find name~"quad9.pem"] 13 | /certificate import file-name=quad9.pem passphrase="" 14 | /file remove quad9.pem 15 | 16 | /ip dns 17 | static remove [find name="dns.quad9.net"] 18 | static add name=dns.quad9.net address=9.9.9.9 comment="Quad9 IPv4" 19 | static add name=dns.quad9.net address=149.112.112.112 comment="Quad9 IPv4 - secondary" 20 | static add name=dns.quad9.net address=2620:fe::9 comment="Quad9 IPv6" 21 | static add name=dns.quad9.net address=2620:fe::fe comment="Quad9 IPv6 - secondary" 22 | 23 | set use-doh-server=https://dns.quad9.net/dns-query verify-doh-cert=yes 24 | 25 | # optional steps 26 | /ip dns set servers="2620:fe::9,9.9.9.9" 27 | /ip dhcp-client set use-peer-dns=no [find] 28 | 29 | # flush existing cache 30 | /ip dns cache flush 31 | 32 | # Post-install step: remove this file manually 33 | # /file remove quad9.rsc 34 | -------------------------------------------------------------------------------- /scripts/auto-update-ros.rsc: -------------------------------------------------------------------------------- 1 | # Ref: https://wiki.mikrotik.com/wiki/Manual:Upgrading_RouterOS#RouterOS_auto-upgrade 2 | /system package update 3 | check-for-updates once 4 | :delay 3s; 5 | :if ( [get status] = "New version is available") do={ install } 6 | -------------------------------------------------------------------------------- /scripts/backup-buttons.rsc: -------------------------------------------------------------------------------- 1 | # Backup button configurations - reset button, mode button. 2 | 3 | # filename: backup-button-config 4 | # policy: ftp, read, write, policy, test 5 | 6 | :global adminEmail 7 | :if ([:typeof $adminEmail] = "nothing" || $adminEmail = "") do={ 8 | :log error "adminEmail is not defined or nil."; :error "Error: Check the log"; } 9 | 10 | :local backupName "buttons" 11 | 12 | :local fileName "$backupName.rsc" 13 | :local emailStatus 14 | 15 | :log info "\nCreating a $backupName backup..." 16 | 17 | # remove existing file, if exists for unknown reason 18 | /file remove [find name=$fileName]; :delay 1s 19 | 20 | # export relevant info 21 | /system routerboard 22 | export file=$fileName 23 | :delay 3s 24 | 25 | /tool e-mail 26 | 27 | :do { send to="$adminEmail" subject="Backup of $backupName" \ 28 | body="See the subject and the attachment." file=$fileName 29 | } on-error={ :log error "Error sending email." } 30 | 31 | :do { :delay 5s; :set emailStatus [get last-status] } while=( $emailStatus = "in-progress" ) 32 | 33 | :if ( $emailStatus = "failed" ) do={ 34 | :log error "Backup failed!" 35 | } else={ 36 | :log info "Backup is taken and is sent to $adminEmail." 37 | } 38 | 39 | /file remove $fileName 40 | -------------------------------------------------------------------------------- /scripts/backup-cron.rsc: -------------------------------------------------------------------------------- 1 | # Backup cron (schedules). 2 | 3 | # filename: backup-cron 4 | # policy: ftp, read, write, policy, test 5 | 6 | :global adminEmail 7 | :if ([:typeof $adminEmail] = "nothing" || $adminEmail = "") do={ 8 | :log error "adminEmail is not defined or nil."; :error "Error: Check the log"; } 9 | 10 | :local backupName "cron" 11 | 12 | :local fileName "$backupName.rsc" 13 | :local emailStatus 14 | 15 | :log info "\nCreating a $backupName backup..." 16 | 17 | # remove existing file, if exists for unknown reason 18 | /file remove [find name=$fileName]; :delay 1s 19 | 20 | # create a backup of cron entries 21 | /system scheduler export file=$fileName 22 | :delay 3s 23 | 24 | /tool e-mail 25 | 26 | :do { send to="$adminEmail" subject="Backup of $backupName" \ 27 | body="See the subject and the attachment." file=$fileName 28 | } on-error={ :log error "Error sending email." } 29 | 30 | :do { :delay 5s; :set emailStatus [get last-status] } while=( $emailStatus = "in-progress" ) 31 | 32 | :if ( $emailStatus = "failed" ) do={ 33 | :log error "Backup failed!" 34 | } else={ 35 | :log info "Backup is taken and is sent to $adminEmail." 36 | } 37 | 38 | /file remove $fileName 39 | -------------------------------------------------------------------------------- /scripts/backup-leases.rsc: -------------------------------------------------------------------------------- 1 | # Backup IP Leases in DHCP Server. 2 | 3 | # filename: backup-leases 4 | # policy: ftp, read, write, policy, test 5 | 6 | :global adminEmail 7 | :if ([:typeof $adminEmail] = "nothing" || $adminEmail = "") do={ 8 | :log error "adminEmail is not defined or nil."; :error "Error: Check the log"; } 9 | 10 | :local backupName "leases" 11 | 12 | # :global scriptsBackupTaken 13 | # :if ([:typeof $scriptsBackupTaken] = "nothing" || $adminEmail = "") do={ :set scriptsBackupTaken false } 14 | # :if ($scriptsBackupTaken = true) do={ :error "Backup of $backupName is already taken since last reboot!" } 15 | 16 | :local fileName "$backupName.rsc" 17 | 18 | :local emailStatus 19 | 20 | # remove existing file, if exists for unknown reason 21 | /file remove [find name=$fileName]; :delay 3s 22 | 23 | :log info "Creating a $backupName backup..." 24 | 25 | # take a backup 26 | /ip dhcp-server lease 27 | export file=$fileName 28 | :delay 3s 29 | 30 | /tool e-mail 31 | 32 | :do { send to="$adminEmail" subject="Backup of $backupName" \ 33 | body="See the subject and the attachment." file=$fileName 34 | } on-error={ :log error "Error sending email." } 35 | 36 | :do { :delay 5s; :set emailStatus [get last-status] } while=( $emailStatus = "in-progress" ) 37 | 38 | :if ( $emailStatus = "failed" ) do={ 39 | :log error "Backup failed!" 40 | } else={ 41 | :log info "Backup is taken and is sent to $adminEmail." 42 | # :set scriptsBackupTaken true 43 | } 44 | 45 | # Optional 46 | :delay 5s; /file remove $fileName 47 | -------------------------------------------------------------------------------- /scripts/backup-scripts.rsc: -------------------------------------------------------------------------------- 1 | # Backup scripts. 2 | 3 | # filename: backup-scripts 4 | # policy: ftp, read, write, policy, test 5 | 6 | :global adminEmail 7 | :if ([:typeof $adminEmail] = "nothing" || $adminEmail = "") do={ 8 | :log error "adminEmail is not defined or nil."; :error "Error: Check the log"; } 9 | 10 | :local backupName "scripts" 11 | :local fileName "$backupName.rsc" 12 | 13 | :local emailStatus 14 | 15 | :log info "\nCreating a $backupName backup..." 16 | 17 | # remove existing file, if exists for unknown reason 18 | /file remove [find name=$fileName]; :delay 3s 19 | 20 | # take a backup 21 | /system script 22 | export file=$fileName 23 | :delay 3s 24 | 25 | /tool e-mail 26 | 27 | :do { send to="$adminEmail" subject="Backup of $backupName" \ 28 | body="See the subject and the attachment." file=$fileName 29 | } on-error={ :log error "Error sending email." } 30 | 31 | :do { :delay 5s; :set emailStatus [get last-status] } while=( $emailStatus = "in-progress" ) 32 | 33 | :if ( $emailStatus = "failed" ) do={ 34 | :log error "Backup failed!" 35 | } else={ 36 | :log info "Backup is taken and is sent to $adminEmail." 37 | } 38 | 39 | # Optional 40 | :delay 5s; /file remove $fileName 41 | -------------------------------------------------------------------------------- /scripts/cloud-backup.rsc: -------------------------------------------------------------------------------- 1 | # Cloud Backup 2 | 3 | # requirement/s: 4 | :global cloudPass 5 | :if ([:typeof $cloudPass] = "nothing" || $cloudPass = "") do={ 6 | :log error "cloudPass is not defined or nil."; :error "Error: Check the log"; } 7 | 8 | # permissions required: ftp, read, write, policy, test 9 | 10 | :log info "\nCreating a new cloud backup..." 11 | 12 | /system backup cloud 13 | 14 | # Remove the backup if exists. 15 | :if ( ([:pick [print as-value] 0]->"status") = "ok" ) do={ 16 | 17 | remove-file number=0 18 | :delay 3s 19 | :log info " Existing cloud backup is removed to create space for a new backup." 20 | 21 | } else={ :log info " No existing cloud backup found."; } 22 | 23 | :log info " A new cloud backup is being created..." 24 | 25 | upload-file action=create-and-upload password=$cloudPass 26 | :delay 30s 27 | 28 | :if ( ([:pick [print as-value] 0]->"status") = "ok" ) do={ 29 | :log info "Cloud backup is successful." 30 | } else={ :log error "Cloud backup failed!" } 31 | -------------------------------------------------------------------------------- /scripts/email-log.rsc: -------------------------------------------------------------------------------- 1 | # Email the generic-log when it reaches the threshold! 2 | 3 | # one-time process to be done when bootstrapping the device 4 | # :local logTopics {"info"; "error"; "warning"; "critical"} 5 | # :foreach topic in=$logTopics do={ :system logging add topics=$topic action=disk } 6 | 7 | # Requirements: adminEmail, logTopics 8 | :global adminEmail 9 | 10 | :if ([:typeof $adminEmail] = "nothing" || $adminEmail = "") do={ 11 | :log error "adminEmail is not defined or nil."; :error "Error: Check the log"; } 12 | 13 | :local emailStatus 14 | :local logFile "log.1.txt" 15 | 16 | # check for "flash" folder 17 | :do { 18 | /file get "flash/log.0.txt" 19 | :set logFile "flash/log.1.txt" 20 | :put "Flash folder found!" 21 | } on-error={ 22 | :put "Flash folder doesn't exist!" 23 | } 24 | 25 | :do { 26 | /file get "$logFile" 27 | } on-error={ 28 | # :log info "$logFile file isn't created yet!"; 29 | :error "$logFile file isn't created yet!"; 30 | } 31 | 32 | # The following gets executed only if the log file is ready! 33 | 34 | :log info "Emailing the log file..." 35 | 36 | /tool e-mail 37 | 38 | :do { 39 | send file="$logFile" subject="Log" body="See sub!" to=$adminEmail 40 | } on-error={ :log error "The log file could not be sent by email." } 41 | 42 | :do { :delay 3s; :set emailStatus [get last-status] } while=( $emailStatus = "in-progress" ) 43 | 44 | :if ( $emailStatus = "succeeded" ) do={ 45 | :log info "The log file is sent to $adminEmail." 46 | } else={ 47 | :log error "Email failed!" 48 | } 49 | 50 | /file remove "$logFile" 51 | -------------------------------------------------------------------------------- /scripts/firmware-check-rb.rsc: -------------------------------------------------------------------------------- 1 | # Notify to upgrade RouterBoard firmware 2 | 3 | # requirement/s: 4 | # policy: read, write, policy, test 5 | # active internet 6 | # $adminEmail 7 | 8 | :global adminEmail 9 | :if ([:typeof $adminEmail] = "nothing" || $adminEmail = "") do={ 10 | :log error "adminEmail is not defined or nil."; :error "Error: Check the log"; } 11 | 12 | :local oldVersion 13 | :local newVersion 14 | 15 | :log info "\nChecking for pending Routerboard firmware update..." 16 | 17 | /system routerboard 18 | :set oldVersion [get current-firmware] 19 | :set newVersion [get upgrade-firmware] 20 | 21 | :if ( $oldVersion != $newVersion ) do={ 22 | :log info "RouterBoard firmware can be upgraded from $oldVersion to $newVersion \n" 23 | /tool e-mail send to="$adminEmail" subject="RouterBoard firmware upgrade!" \ 24 | body="An upgrade from $oldVersion to $newVersion is pending!" 25 | } else={ 26 | :log info "RouterBoard firmware is up to date." 27 | } 28 | -------------------------------------------------------------------------------- /scripts/firmware-check-ros-v2.rsc: -------------------------------------------------------------------------------- 1 | # Alert upon new Router OS Version 2 | 3 | # requirement/s: 4 | # policy: read, write, policy, test 5 | # active internet 6 | # $adminEmail 7 | 8 | :global adminEmail 9 | :if ([:typeof $adminEmail] = "nothing" || $adminEmail = "") do={ 10 | :log error "adminEmail is not defined or nil."; :error "Error: Check the log"; } 11 | 12 | :local versionStatus 13 | 14 | :log info "\nChecking for new version of Router OS..." 15 | 16 | /system package update 17 | check-for-updates once 18 | 19 | :local updateStatus "incomplete" 20 | :do { 21 | :delay 2s 22 | 23 | :set $updateStatus [get status] 24 | 25 | :if ($updateStatus = "ERROR: no internet connection") do={ :error "ERROT: no internet connection"; } 26 | :if ($updateStatus = "ERROR: connection timed out") do={ :error "ERROR: connection timed out"; } 27 | 28 | :if ($updateStatus = "getting changelog...") do={ :set $updateStatus "incomplete" } 29 | :if ($updateStatus = "finding out latest version...") do={ :set $updateStatus "incomplete" } 30 | 31 | :if ($updateStatus = "New version is available" ) do={ } 32 | :if ($updateStatus = "System is already up to date" ) do={ } 33 | 34 | } while=( $updateStatus = "incomplete" ) 35 | 36 | :local installedVersion [get installed-version] 37 | :local latestVersion [get latest-version] 38 | 39 | :if ( $updateStatus = "New version is available" ) do={ 40 | # alternative method 41 | # :if ( installedVersion != $latestVersion ) do={ 42 | :log info "A new update is available for Router OS." 43 | /tool e-mail send to="$adminEmail" \ 44 | subject="Software Update is Available" \ 45 | body="A new Router OS update is available... 46 | 47 | Installed Version: $installedVersion 48 | Latest Version: $latestVersion 49 | " 50 | } else={ 51 | :log info "Router OS is up to date." 52 | } 53 | -------------------------------------------------------------------------------- /scripts/firmware-check-ros.rsc: -------------------------------------------------------------------------------- 1 | # Alert upon new Router OS Version 2 | 3 | # requirement/s: 4 | # policy: read, write, policy, test 5 | # active internet 6 | # $adminEmail 7 | 8 | :global adminEmail 9 | :if ([:typeof $adminEmail] = "nothing" || $adminEmail = "") do={ 10 | :log error "adminEmail is not defined or nil."; :error "Error: Check the log"; } 11 | 12 | :local versionStatus 13 | 14 | :log info "\nChecking for new version of Router OS..." 15 | 16 | /system package update 17 | check-for-updates once 18 | 19 | :do { 20 | :delay 3s 21 | 22 | :set $versionStatus [get status] 23 | # alternative way to get the above info 24 | # :set $versionStatus ([print as-value]->"status") 25 | } while=( $versionStatus = "finding out latest version..." ) 26 | 27 | :local installedVersion [get installed-version] 28 | :local latestVersion [get latest-version] 29 | 30 | :if ( $versionStatus = "New version is available" ) do={ 31 | # alternative method 32 | # :if ( installedVersion != $latestVersion ) do={ 33 | :log info "A new update is available for Router OS." 34 | /tool e-mail send to="$adminEmail" \ 35 | subject="Software Update is Available" \ 36 | body="A new Router OS update is available... 37 | 38 | Installed Version: $installedVersion 39 | Latest Version: $latestVersion 40 | " 41 | } else={ 42 | :log info "Router OS is up to date." 43 | } 44 | -------------------------------------------------------------------------------- /scripts/firmware-check.rsc: -------------------------------------------------------------------------------- 1 | # Alert upon new Router OS Version and pending RouterBoard firmware update! 2 | 3 | # requirement/s: 4 | # policy: read, write, policy, test 5 | # active internet 6 | # $adminEmail 7 | 8 | :global adminEmail 9 | :if ([:typeof $adminEmail] = "nothing" || $adminEmail = "") do={ 10 | :log error "adminEmail is not defined or nil."; :error "Error: Check the log"; } 11 | 12 | :local versionStatus 13 | 14 | :log info "\nChecking for new version of Router OS..." 15 | 16 | /system package update 17 | check-for-updates once 18 | 19 | :do { 20 | :delay 3s 21 | 22 | :set $versionStatus [get status] 23 | # alternative way to get the above info 24 | # :set $versionStatus ([print as-value]->"status") 25 | } while=( $versionStatus = "finding out latest version..." ) 26 | 27 | :local installedVersion [get installed-version] 28 | :local latestVersion [get latest-version] 29 | 30 | :if ( $versionStatus = "New version is available" ) do={ 31 | # alternative method 32 | # :if ( installedVersion != $latestVersion ) do={ 33 | :log info "A new update is available for Router OS." 34 | /tool e-mail send to="$adminEmail" \ 35 | subject="Software Update is Available" \ 36 | body="A new Router OS update is available... 37 | 38 | Installed Version: $installedVersion 39 | Latest Version: $latestVersion 40 | " 41 | } else={ 42 | :log info "Router OS is up to date." 43 | } 44 | 45 | # Notify to upgrade RouterBoard Firmware 46 | 47 | # requirement/s: 48 | # policy: read, write, policy, test 49 | # active internet 50 | # $adminEmail 51 | 52 | :global adminEmail 53 | :local oldVersion 54 | :local newVersion 55 | 56 | :log info "\nChecking for pending Routerboard firmware update..." 57 | 58 | /system routerboard 59 | :set oldVersion [get current-firmware] 60 | :set newVersion [get upgrade-firmware] 61 | 62 | :if ( $oldVersion != $newVersion ) do={ 63 | :log info "RouterBoard firmware can be upgraded from $oldVersion to $newVersion \n" 64 | /tool e-mail send to="$adminEmail" subject="RouterBoard firmware upgrade!" \ 65 | body="An upgrade from $oldVersion to $newVersion is pending!" 66 | } else={ 67 | :log info "RouterBoard Firmware is up to date." 68 | } 69 | -------------------------------------------------------------------------------- /scripts/hap-ac2-bootstrap.rsc: -------------------------------------------------------------------------------- 1 | :global myCountry "India"; 2 | :global myTimezone "Asia/Kolkata"; 3 | :global myIdentity "Mikrotik"; 4 | :global mySSID "Mikrotik"; 5 | :global myPassword; 6 | 7 | # please change passwords to something unique 8 | :global mainWIFIpass "RouterOSv6"; 9 | :global guestWIFIpass "ROS6Guests"; 10 | 11 | # override the default values here 12 | :set myIdentity "Mikrotik #1 hAP ac2"; 13 | :set mySSID "mikro1-on" 14 | :set guestSSID "mikro1-gn" 15 | 16 | :set myPassword [:pick ([/cert scep-server otp generate as-value minutes-valid=1]->"password") 0 20] 17 | :set mainWIFIpass [:pick ([/cert scep-server otp generate as-value minutes-valid=1]->"password") 0 20] 18 | :set guestWIFIpass [:pick ([/cert scep-server otp generate as-value minutes-valid=1]->"password") 0 20] 19 | 20 | # my subnet 21 | :global mySubnetPrefix "10.88.21"; 22 | :global mySubnetCIDR "10.88.210.0/24"; 23 | :global dhcpServerIP "10.88.210.1"; 24 | :global dhcpPoolRange "10.88.210.88-10.88.210.254"; 25 | :global dhcpName "my-dhcp"; 26 | :global myBridgeAddress "10.88.210.1/24"; 27 | 28 | # Guest subnet 29 | :global guestSubnetCIDR "10.88.211.0/24"; 30 | :global guestPoolRange "10.88.211.88-10.88.211.254"; 31 | :global guestNetworkName "Mikrotik-Guests"; 32 | 33 | # SSH 34 | :global sshUserName "pothi"; 35 | 36 | ### ------------------------------------------------------------------------------------ ### 37 | # Generic Tweaks # 38 | ### ------------------------------------------------------------------------------------ ### 39 | 40 | # Configure Identity 41 | /system identity set name=$myIdentity; 42 | 43 | # Minor Tweaks 44 | /system routerboard settings set init-delay=3 45 | /interface detect-internet 46 | set detect-interface-list=WAN 47 | set lan-interface-list=LAN 48 | set wan-interface-list=all 49 | set internet-interface-list=all 50 | 51 | # Change subnet 52 | /ip pool add name=$dhcpName ranges=$dhcpPoolRange; 53 | /ip pool remove default-dhcp; 54 | 55 | /ip dhcp-server remove defconf; 56 | /ip dhcp-server add name=$dhcpName address-pool=$dhcpName interface=bridge lease-time=10m disabled=no; 57 | 58 | /ip dhcp-server network add address=$mySubnetCIDR gateway=$dhcpServerIP dns-server=$dhcpServerIP; 59 | /ip dhcp-server network remove [find dns-server=192.168.88.1]; 60 | 61 | /ip address add address=$myBridgeAddress interface=bridge; 62 | /ip address remove [find address="192.168.88.1/24"]; 63 | 64 | /ip dns static set numbers=[find name=router.lan] address=$dhcpServerIP; 65 | 66 | # Configure Guest Network and Firewall 67 | 68 | # Wireless tweaks 69 | 70 | # install public SSH key 71 | :put "Configuring SSH..."; 72 | { 73 | :local result [ /tool fetch https://launchpad.net/~pothi/+sshkeys dst-path=pothi-ssh-key-rsa as-value]; 74 | :do { :delay 2s } while=( $result->"status" != "finished" ) 75 | } 76 | /user ssh-keys import public-key-file=pothi-ssh-key-rsa; 77 | /file remove pothi-ssh-key-rsa; 78 | 79 | # Reduce disk activity 80 | /ip dhcp-server config set store-leases-disk=never; 81 | 82 | # Configure NTP Client 83 | /system ntp client set primary-ntp=[ :resolve pool.ntp.org ]; 84 | /system ntp client set secondary-ntp=[ :resolve time.cloudflare.com ]; 85 | 86 | # Enable mode-button 87 | :global modeButtonScriptName "wifi-enable"; 88 | /system script add name=$modeButtonScriptName source={/interface wireless enable [find];}; 89 | /system routerboard mode-button set on-event=$modeButtonScriptName enabled=yes; 90 | 91 | # WiFi 92 | # WiFi Channels 93 | /interface wireless channels 94 | add band=2ghz-onlyn frequency=2412 list="2.4ghz list" name=channel-1 width=20 95 | add band=2ghz-onlyn frequency=2437 list="2.4ghz list" name=channel-6 width=20 96 | add band=2ghz-onlyn frequency=2462 list="2.4ghz list" name=channel-11 width=20 97 | 98 | /interface wireless 99 | set [ find default-name=wlan1 ] band=2ghz-onlyn country=india disabled=no installation=indoor mode=ap-bridge ssid=$mySSID wireless-protocol=802.11 \ 100 | wmm-support=enabled wps-mode=disabled scan-list="2.4ghz list" 101 | set [ find default-name=wlan2 ] band=5ghz-n/ac country=india disabled=no installation=indoor mode=ap-bridge ssid=$mySSID wireless-protocol=802.11 \ 102 | wmm-support=enabled wps-mode=disabled skip-dfs-channels=all 103 | /interface wireless security-profiles 104 | set [ find default=yes ] mode=dynamic-keys authentication-types=wpa2-psk wpa2-pre-shared-key=$mainWIFIpass 105 | 106 | # Cron 107 | /system scheduler 108 | add interval=1d name=wifi-enable on-event="/interface wireless enable [find];" policy=ftp,reboot,read,write,policy,test,password,sniff,sensitive,romon start-date=dec/11/2021 \ 109 | start-time=05:55:51 110 | add interval=1d name=wifi-disable on-event="/interface wireless disable [find];" policy=ftp,reboot,read,write,policy,test,password,sniff,sensitive,romon start-date=dec/11/2021 \ 111 | start-time=23:06:25 112 | -------------------------------------------------------------------------------- /scripts/init.rsc: -------------------------------------------------------------------------------- 1 | # Initialize the router with default values, run backup scripts and check for updates! 2 | 3 | # Version: 2 4 | 5 | # changelog 6 | # version: 2 7 | # - date: 2022-11-18 8 | # - introduction of timeout to check internet 9 | 10 | :global adminEmail "noreply@example.com" 11 | :global cloudPass "" 12 | 13 | :local isUP 0 14 | :local timeout 5 15 | 16 | /interface/detect-internet 17 | set detect-interface-list=WAN 18 | state 19 | 20 | :do { 21 | :delay 60s 22 | :set $internetStatus ([:pick [print as-value] 0]->"state") 23 | # :log info "Waiting for internet..." 24 | 25 | :set isUP ($isUP+1) 26 | :if ($isUP = $timeout) do={ :error "Internet timed out after $timeout minutes!" } 27 | 28 | } while ($internetStatus != "internet") 29 | 30 | # :log info "Connected to internet." 31 | 32 | :log info "Init script started." 33 | 34 | /system script 35 | 36 | :local commonScripts {"cloud-backup"; "firmware-check"} 37 | :local initScripts ("wifi-enable", $commonScripts) 38 | 39 | :foreach scriptName in $initScripts do={ 40 | :do { run $scriptName } on-error={:log error "Error running $scriptName"} 41 | :delay 30s 42 | } 43 | 44 | :local currentHour [:tonum [:pick [/system clock get time] 0 2]] 45 | 46 | :if ($currentHour < 12) do={ 47 | :local backupScripts {"backup-cron"; "backup-scripts"} 48 | :foreach scriptName in $backupScripts do={ 49 | :do { run $scriptName } on-error={:log error "Error running $scriptName"} 50 | :delay 30s 51 | } 52 | } else={ 53 | :log info "Automated backups aren't taken after 12 noon." 54 | } 55 | 56 | :log info "Init script ended." 57 | -------------------------------------------------------------------------------- /scripts/ntp-client-v6.rsc: -------------------------------------------------------------------------------- 1 | # List of public servers... https://gist.github.com/mutin-sa/eea1c396b1e610a2da1e5550d94b0453 2 | 3 | # variables 4 | # timezone 5 | :local tz 6 | :set tz "+05:30" 7 | 8 | # To be used as the primary NTP server 9 | :local ipNTP 10 | :local ipNTPcomment 11 | # IP based NTP server - when DNS is unavailable. 12 | :set ipNTP "128.138.140.44" 13 | :set ipNTPcomment "From https://tf.nist.gov/tf-cgi/servers.cgi" 14 | 15 | # To be used as the secondary NTP server 16 | :local poolNTPorg 17 | :set poolNTPorg [:resolve pool.ntp.org] 18 | 19 | # To be used for DNS based NTP servers 20 | :local ntp1 21 | :local ntp2 22 | :set ntp1 "time.cloudflare.com" 23 | :set ntp2 "time.google.com" 24 | 25 | :put "Primary NTP: $ipNTP ($ipNTPcomment)" 26 | :put "Secondary NTP: $poolNTPorg (pool.ntp.org)" 27 | :put "DNS NTP 1: $ntp1" 28 | :put "DNS NTP 2: $ntp2" 29 | 30 | # configure timezone 31 | # /system clock manual set time-zone=$tz 32 | :put "Timezone: $tz\n" 33 | :put "Clock info..." 34 | 35 | /system clock print 36 | 37 | # Find Router OS version 38 | 39 | :local rosVersion 40 | :set rosVersion [:tonum [:pick [/system resource get version] 0 1]] 41 | # following works as well. 42 | # :set rosVersion [:pick [/system/routerboard/get current-firmware] 0 1] 43 | 44 | :put "\nRouter OS Version: $rosVersion\n" 45 | 46 | 47 | if ( $rosVersion = 6 ) do={ 48 | /system ntp client 49 | set primary-ntp=128.138.140.44 50 | set secondary-ntp=[ :resolve pool.ntp.org ] 51 | set server-dns-names=time.cloudflare.com,time.google.com 52 | } 53 | 54 | /system ntp client set enabled=yes 55 | 56 | 57 | :put "NTP client info..." 58 | /system ntp client print 59 | -------------------------------------------------------------------------------- /scripts/ntp-client-v7.rsc: -------------------------------------------------------------------------------- 1 | # List of public servers... https://gist.github.com/mutin-sa/eea1c396b1e610a2da1e5550d94b0453 2 | 3 | # variables 4 | # timezone 5 | :local tz 6 | :set tz "+05:30" 7 | 8 | # To be used as the primary NTP server 9 | :local ipNTP 10 | :local ipNTPcomment 11 | # IP based NTP server - when DNS is unavailable. 12 | :set ipNTP "128.138.140.44" 13 | :set ipNTPcomment "From https://tf.nist.gov/tf-cgi/servers.cgi" 14 | 15 | # To be used as the secondary NTP server 16 | :local poolNTPorg 17 | :set poolNTPorg [:resolve pool.ntp.org] 18 | 19 | # To be used for DNS based NTP servers 20 | :local ntp1 21 | :local ntp2 22 | :set ntp1 "time.cloudflare.com" 23 | :set ntp2 "time.google.com" 24 | 25 | :put "Primary NTP: $ipNTP ($ipNTPcomment)" 26 | :put "Secondary NTP: $poolNTPorg (pool.ntp.org)" 27 | :put "DNS NTP 1: $ntp1" 28 | :put "DNS NTP 2: $ntp2" 29 | 30 | # configure timezone 31 | # /system clock manual set time-zone=$tz 32 | :put "Timezone: $tz\n" 33 | :put "Clock info..." 34 | 35 | /system clock print 36 | 37 | # Find Router OS version 38 | 39 | :local rosVersion 40 | :set rosVersion [:tonum [:pick [/system resource get version] 0 1]] 41 | # following works as well. 42 | # :set rosVersion [:pick [/system/routerboard/get current-firmware] 0 1] 43 | 44 | :put "\nRouter OS Version: $rosVersion\n" 45 | 46 | 47 | if ( $rosVersion = 7 ) do={ 48 | /system ntp client servers 49 | add address=128.138.140.44 comment="NIST.gov" 50 | add address=[ :resolve pool.ntp.org ] comment="pool.ntp.org" 51 | add address=time.google.com 52 | add address=time.cloudflare.com 53 | } 54 | 55 | /system ntp client set enabled=yes 56 | 57 | 58 | :put "NTP client info..." 59 | /system ntp client print 60 | -------------------------------------------------------------------------------- /scripts/temparature.rsc: -------------------------------------------------------------------------------- 1 | # Find temparature and alert if threshold is reached. 2 | 3 | :local t 4 | :local threshold 60 5 | 6 | :do { 7 | :set t [/system health get value-name=value number=[find name=cpu-temperature]] 8 | } on-error={ :set t -1 } 9 | 10 | :put $t 11 | 12 | :if ( $t < 0 ) do={ 13 | :log warn "Temparature reading could not be fetched." 14 | :error "Temparature reading could not be fetched." 15 | } 16 | 17 | :if ( $t > $threshold ) do={ 18 | :put "Temp exceeded the limit ($limit)." 19 | :log warning "Temp exceeded the limit ($threshold)." 20 | } 21 | :log info "Current temparature: $t" 22 | -------------------------------------------------------------------------------- /scripts/toggle-tx-speed.rsc: -------------------------------------------------------------------------------- 1 | # Script to toggle wlan speeds. 2 | 3 | :log info "Toggle TX Limits script is executed." 4 | 5 | :local txLimit 6 | 7 | :set txLimit [/interface/wireless/get [find] default-ap-tx-limit] 8 | 9 | :tonum $txLimit 10 | 11 | :if ( $txLimit = 0 ) do={ 12 | /interface/wireless/set [find] default-ap-tx-limit=2M 13 | :log info "Wlan speed is restricted to 2Mbps." 14 | } else={ 15 | /interface/wireless/set wlan1 default-ap-tx-limit=0 16 | :log info "Wlan doesn't have speed limits now." 17 | } 18 | -------------------------------------------------------------------------------- /scripts/unknown-device.rsc: -------------------------------------------------------------------------------- 1 | # Modified from https://forum.mikrotik.com/viewtopic.php?t=181433 2 | 3 | :global adminEmail 4 | 5 | # :log info "Success" 6 | 7 | /ip dhcp-server lease 8 | :if (($leaseBound=1) && ([find where dynamic mac-address=$leaseActMAC]!="")) do { 9 | :local leaseHostName $"lease-hostname" 10 | :do { 11 | :tool e-mail send \ 12 | to=$adminEmail \ 13 | subject="Unknown Device Alert [MAC: $leaseActMAC]" \ 14 | body="The following unknown device received a dynamic IP address: 15 | Mac: $leaseActMAC 16 | Ip: $leaseActIP, 17 | Host: $leaseHostName, 18 | Bound: $leaseBound" 19 | :log info "Unknown Device: $leaseActMAC, $leaseActIP, $leaseHostName" 20 | } on-error={:log error "Failed to send alert email upon unknown device."} 21 | }} 22 | 23 | -------------------------------------------------------------------------------- /test-snippets/README.md: -------------------------------------------------------------------------------- 1 | # Test Snippets 2 | 3 | These are not full-fledged scripts. Just snippets to test a single unit of action such as detecting internet or detecting DNS. I hope someone finds it useful! 4 | -------------------------------------------------------------------------------- /test-snippets/email-dns-bug.rsc: -------------------------------------------------------------------------------- 1 | # How to reproduce 2 | # 1. Configure email sending. 3 | # 2. Turn off DNS servers and/or DoH server 4 | # 3. Clear DNS cache 5 | # 4. Run this script 6 | # 5. On ideal conditions, we'd get "A friendly message" in the log 7 | # 6. Due to bug, we get nothing we email sending fails upon DNS failure. 8 | 9 | :do { 10 | /tool e-mail send to=kpothi@gmail.com body="Body Message" subject="Sample subject" 11 | } on-error={ :log error "A friendly message" } 12 | 13 | :log warn "This message should not be shown" 14 | -------------------------------------------------------------------------------- /test-snippets/test-array.rsc: -------------------------------------------------------------------------------- 1 | :local scripts 2 | 3 | :set scripts {"lease";"buttons"} 4 | 5 | :foreach script in=$scripts do={ 6 | :put $script; 7 | } 8 | -------------------------------------------------------------------------------- /test-snippets/test-detect-internet-minspeed.rsc: -------------------------------------------------------------------------------- 1 | :while ( $minSpeed = 0 ) do={ 2 | :delay 60s; 3 | # :log info "Minimum speed hasn't reached, yet." 4 | } 5 | # :log info "Minimum speed has reached." 6 | 7 | # :delay 900s; :if ($minSpeed = 0) do={ :log error "No (stable) internet for 15 minutes"; :error "see log" } 8 | 9 | -------------------------------------------------------------------------------- /test-snippets/test-detect-internet.rsc: -------------------------------------------------------------------------------- 1 | # requirement: /interface detect-internet set detect-interface-list=WAN 2 | 3 | /interface detect-internet 4 | # set detect-interface-list=WAN 5 | state 6 | 7 | :do { 8 | :log info "Waiting for internet..." 9 | :set $internetStatus ([:pick [print as-value] 0]->"state") 10 | :delay 3s 11 | } while ($internetStatus != "internet") 12 | 13 | :log info "Connected to internet." 14 | -------------------------------------------------------------------------------- /test-snippets/test-empty-env-var: -------------------------------------------------------------------------------- 1 | :global adminEmail 2 | 3 | :if ([:typeof $adminEmail] = "nothing" || $adminEmail = "") do={ :log error "Admin Email is not defined or nil."; :error "Admin Email is not defined or nil."; } else={ :put "We are good to proceed!" } 4 | 5 | # :if ($adminEmail = "") do={ :log error "Admin Email is nil."; :error "Admin Email is nil."; } 6 | 7 | :put "This should not be visible if admin email is not defined or nil!" 8 | -------------------------------------------------------------------------------- /test-snippets/test-generate-password: -------------------------------------------------------------------------------- 1 | :global myPassword; 2 | 3 | :set myPassword [:pick ([/cert scep-server otp generate as-value minutes-valid=1]->"password") 0 20] 4 | :put "Your new password is..." 5 | :put $myPassword 6 | -------------------------------------------------------------------------------- /test-snippets/test-log: -------------------------------------------------------------------------------- 1 | # Email the generic-log when it reaches the threshold! 2 | 3 | :global adminEmail 4 | :local emailStatus 5 | :local logFile "genericLog.1.txt" 6 | :local fileContent "temp" 7 | 8 | :do { 9 | if ( [/file get "flash/$logFile" ] != "no such item" ) do={ :log info "Log file found!" } 10 | } on-error={ :log warning "Log file isn't big enough!" } 11 | 12 | :put $fileContent 13 | -------------------------------------------------------------------------------- /test-snippets/test-timesync.rsc: -------------------------------------------------------------------------------- 1 | # Used to fill logs at every few seconds to find when the cloud timesync happens in RouterOS v6 2 | # It can be used for multiple other use cases too. 3 | 4 | :local i 0 5 | 6 | :do { 7 | :delay 10s 8 | :set i ($i+10) 9 | :log info "Time passed since boot: $i seconds" 10 | } while ($i < 600) 11 | -------------------------------------------------------------------------------- /test-snippets/test-version-7.19.rsc: -------------------------------------------------------------------------------- 1 | # find RouterOS version 2 | 3 | :local rosVersion 4 | :set rosVersion [:pick [/system/routerboard/get current-firmware] 0 1] 5 | 6 | :if ($rosVersion != 7) do={ 7 | :error "We need Router OS version 7 to run this script - current ROS version $rosVersion." 8 | } 9 | 10 | :local rosVersionMinor 11 | :set rosVersionMinor [:pick [/system/routerboard/get current-firmware] 2 4] 12 | 13 | :if ($rosVersionMinor >= 19) do={ 14 | :put "We have the required Router OS version (or greater) - $rosVersion.$rosVersionMinor" 15 | } else={ 16 | :put "We use the Router OS version $rosVersion.$rosVersionMinor that is less than the required version (7.19)." 17 | } 18 | -------------------------------------------------------------------------------- /tik-forum-users/wan-monitor.rsc: -------------------------------------------------------------------------------- 1 | # ref: https://forum.mikrotik.com/viewtopic.php?p=671934 2 | # date: Feb 2018 3 | 4 | :if ([:len [/system scheduler find name=wanmonitor]]=0) do={ 5 | :log warning "creating wan monitor scheduler" 6 | /system scheduler add name=wanmonitor interval=1h on-event="/system script run wanmonitor" start-time=startup comment="'wanmonitor' checking internet connection(s)" 7 | } else={ 8 | :if ([/system scheduler get value-name=on-event [/system scheduler find name=wanmonitor]]!="/system script run wanmonitor") do={ 9 | :log warning "updating wan monitor scheduler" 10 | /system scheduler set on-event="/system script run wanmonitor" [/system scheduler find name=wanmonitor] 11 | } 12 | } 13 | 14 | :local wmCheck do={ 15 | #Configuration 16 | :local fconfig [:parse [/system script get wanmonitor.cfg source]] 17 | :local cfg [$fconfig] 18 | :local WANS ($cfg->"Interfaces") 19 | :local RUNONUP ($cfg->"ScriptOnUp") 20 | :local STORAGE ($cfg->"Storage") 21 | :local TGID ($cfg->"Telegram") 22 | 23 | #Inputs 24 | :local Wan [:tostr $1] 25 | :local Hosts [:toarray $2] 26 | :if ([:len $Hosts]=0) do={ 27 | :set $Hosts "64.6.64.6,4.2.2.1" 28 | } 29 | 30 | #Settings 31 | :local Runtime 0 32 | :local Retries 2 33 | 34 | #Counters 35 | :local Checks 0 36 | :local Failures 0 37 | 38 | #telegram command 39 | :local telegram 40 | :if ([:len [/system script find name=telegram]]>0) do={ 41 | :set telegram [:parse [/system script get telegram source]] 42 | } 43 | 44 | ## Get gateway ip address 45 | :local wmGateway do={ 46 | :if ([:len [/ip dhcp-client find where interface=$wan]]>0) do={ 47 | :return [/ip dhcp-client get value-name=gateway [find interface=[:tostr $wan]]] 48 | } else={ 49 | :return [$wan] 50 | } 51 | } 52 | 53 | ## Get public ip 54 | :local wmAddress do={ 55 | ## Check if interface have dhcp-client return address via myip.dnsomatic.com 56 | :if ([:len [/ip dhcp-client find where interface=$wan]]>0) do={ 57 | :local count 0 58 | :local wgate [/ip dhcp-client get value-name=gateway [find interface=[:tostr $wan]]] 59 | /ip route add comment="tempory route for 'dnsomatic.com'..." distance=1 dst-address=[:resolve "myip.dnsomatic.com"] gateway=$wgate 60 | /ip route add comment="tempory route for 'dnsomatic.com'..." distance=2 dst-address=[:resolve "myip.dnsomatic.com"] type=blackhole 61 | :while (([:len [/file find name="wan.ip"]]=0) and ($count<10)) do={ 62 | :delay 1s 63 | /tool fetch url="http://myip.dnsomatic.com/" mode=http dst-path="wan.ip" 64 | :set count ($count+1) 65 | } 66 | /ip route remove [/ip route find where comment="tempory route for 'dnsomatic.com'..."] 67 | :if ([:len [/file find name="wan.ip"]]>0) do={ 68 | :local results [file get "wan.ip" contents]; 69 | /file remove [/file find name="wan.ip"] 70 | :return $results 71 | } 72 | } 73 | ## Check if interface have ip address 74 | :if ([:typeof [/ip address get value-name=address [/ip address find interface=$wan]]]!="nil") do={ 75 | :return [:pick [/ip address get value-name=address [/ip address find interface=$wan]] 0 [:find [/ip address get value-name=address [/ip address find interface=$wan]] "/"]] 76 | } else={ 77 | :return "0.0.0.0" 78 | } 79 | } 80 | 81 | ## Wan enable/disable 82 | :local wmMode do={ 83 | :local count 84 | ## Set firewall nat 'masquerade' enable or disable 85 | :if ([:len [/ip firewall nat find where out-interface=$wan and action=masquerade]]>0) do={ 86 | if ([:tostr $mode]="enable") do={ 87 | :local masquerade false 88 | } else={ 89 | :local masquerade true 90 | } 91 | /ip firewall nat set disabled=$masquerade [/ip firewall nat find where out-interface=$wan and action=masquerade] 92 | } 93 | ## Set add-default-route yes or no / true or false 94 | :if ([:pick [/interface get value-name=type $wan] ([:find [/interface get value-name=type $wan] "-"]+1) [:len [/interface get value-name=type $wan]]]="out") do={ 95 | :local drc 96 | if ([:tostr $mode]="enable") do={ 97 | :set $drc true 98 | } else={ 99 | :set $drc false 100 | } 101 | :if (([:pick [/interface get value-name=type $wan] 0 [:find [/interface get value-name=type $wan] "-"]]="pppoe") && ([/interface pppoe-client get value-name=add-default-route $wan]!=$drc)) do={ 102 | /interface pppoe-client set add-default-route=$drc $wan 103 | } 104 | :if (([:pick [/interface get value-name=type $wan] 0 [:find [/interface get value-name=type $wan] "-"]]="l2tp") && ([/interface l2tp-client get value-name=add-default-route $wan]!=$drc)) do={ 105 | /interface l2tp-client set add-default-route=$drc $wan 106 | } 107 | :if (([:pick [/interface get value-name=type $wan] 0 [:find [/interface get value-name=type $wan] "-"]]="ppp") && ([/interface ppp-client get value-name=add-default-route $wan]!=$drc)) do={ 108 | /interface ppp-client set add-default-route=$drc $wan 109 | } 110 | :if (([:pick [/interface get value-name=type $wan] 0 [:find [/interface get value-name=type $wan] "-"]]="sstp") && ([/interface sstp-client get value-name=add-default-route $wan]!=$drc)) do={ 111 | /interface sstp-client set add-default-route=$drc $wan 112 | } 113 | :log warning ("interface $[:pick [/interface get value-name=type $wan] 0 [:find [/interface get value-name=type $wan] "-"]]-client '$wan' set 'add-default-route' to '$drc'"); 114 | } else={ 115 | :if ([:len [/ip dhcp-client find interface=$wan]]>0) do={ 116 | :local drd 117 | if ([:tostr $mode]="enable") do={ 118 | :set $drd "yes" 119 | } else={ 120 | :set $drd "no" 121 | } 122 | :if ([/ip dhcp-client get value-name=add-default-route [/ip dhcp-client find interface=$wan]]!=$drd) do={ 123 | /ip dhcp-client set add-default-route=$drd [/ip dhcp-client find interface=$wan] 124 | :log warning ("'$wan' dhcp-client (".[/interface get value-name=type $wan].") set 'add-default-route' to '$drd'") 125 | } 126 | } 127 | } 128 | } 129 | 130 | ## Reset interface 131 | :local wmReset do={ 132 | :local count 133 | :if ([/interface get value-name=type $wan]="lte") do={ 134 | /system routerboard usb power-reset duration=1s 135 | :log warning "usb power ('$wan') reset..." 136 | :delay 3s 137 | :set count 0 138 | :while (([:len [/interface find name=$wan]]=0) and ($count<30)) do={ 139 | :delay 1s 140 | :set count ($count+1) 141 | } 142 | :log warning "usb device ('$wan') was connected" 143 | :set count 0 144 | :while (([/interface get value-name=running [/interface find name=$wan]]=false) and ($count<30)) do={ 145 | :delay 1s 146 | :set count ($count+1) 147 | } 148 | :log warning "interface ('$wan') is running" 149 | :delay 3s 150 | :if ([:len [/ip dhcp-client find interface=$wan]]>0) do={ 151 | :delay 3s 152 | :set count 0 153 | :while (([/ip dhcp-client get value-name=status [/ip dhcp-client find interface=$wan]]!="bound") and ($count<30)) do={ 154 | :delay 1s 155 | :set count ($count+1) 156 | } 157 | :log warning "dhcp-client ('$wan') bounded" 158 | } 159 | } else={ 160 | /interface disable $wan 161 | :log warning "interface '$wan' was disabled" 162 | :delay 500ms 163 | /interface enable $wan; 164 | :log warning "interface '$wan' was enabled" 165 | :delay 3s 166 | :if ([:len [/ip dhcp-client find interface=$wan]]>0) do={ 167 | :set count 0 168 | :while (([/ip dhcp-client get value-name=status [/ip dhcp-client find interface=$wan]]!="bound") and ($count<30)) do={ 169 | :delay 1s 170 | :set count ($count+1) 171 | } 172 | :log warning "dhcp-client ('$wan') bounded" 173 | :delay 3s 174 | } 175 | :if ([:pick [/interface get value-name=type $wan] ([:find [/interface get value-name=type $wan] "-"]+1) [:len [/interface get value-name=type $wan]]]="out") do={ 176 | :set count 0 177 | :while (([/interface get value-name=running [/interface find name=$wan]]=false) and ($count<30)) do={ 178 | :delay 1s 179 | :set count ($count+1) 180 | } 181 | :log warning "interface ('$wan') is running" 182 | :delay 3s 183 | } 184 | } 185 | } 186 | 187 | ## PPP profile script 188 | :local onConnected do={ 189 | ## Add script to ppp profile on up ('connected') 190 | :if ([:pick [/interface get value-name=type $wan] ([:find [/interface get value-name=type $wan] "-"]+1) [:len [/interface get value-name=type $wan]]]="out") do={ 191 | :local script "/interface $[:pick [/interface get value-name=type $wan] 0 [:find [/interface get value-name=type $wan] "-"]]-client monitor $wan once do={\n :local uptime ([:tonum [:pick [:tostr \$uptime] 0 2]]*60*60+[:tonum [:pick [:tostr \$uptime] 3 5]]*60+[:tonum [:pick [:tostr \$uptime] 6 8]])\n}\n:if (\$uptime<3) do={\n /tool netwatch remove [/tool netwatch find comment=$wan]\n :local script [:parse [/system script get wanmonitor source]]\n \$script wan=$wan hosts=$[:tostr $hosts]\n\n}" 192 | :if (([:pick [/interface get value-name=type $wan] 0 [:find [/interface get value-name=type $wan] "-"]]="pppoe") and ([:typeof [:find [/ppp profile get value-name=on-up [/interface pppoe-client get value-name=profile $wan]] "\$script wan=$wan"]]="nil")) do={ 193 | /ppp profile set on-up=([/ppp profile get value-name=on-up [/interface pppoe-client get value-name=profile $wan]]."\n".$script) [/interface pppoe-client get value-name=profile $wan] 194 | } 195 | :if (([:pick [/interface get value-name=type $wan] 0 [:find [/interface get value-name=type $wan] "-"]]="l2tp") and ([:typeof [:find [/ppp profile get value-name=on-up [/interface l2tp-client get value-name=profile $wan]] "\$script wan=$wan"]]="nil")) do={ 196 | /ppp profile set on-up=([/ppp profile get value-name=on-up [/interface l2tp-client get value-name=profile $wan]]."\n".$script) [/interface l2tp-client get value-name=profile $wan] 197 | } 198 | :if (([:pick [/interface get value-name=type $wan] 0 [:find [/interface get value-name=type $wan] "-"]]="ppp") and ([:typeof [:find [/ppp profile get value-name=on-up [/interface ppp-client get value-name=profile $wan]] "\$script wan=$wan"]]="nil")) do={ 199 | /ppp profile set on-up=([/ppp profile get value-name=on-up [/interface ppp-client get value-name=profile $wan]]."\n".$script) [/interface ppp-client get value-name=profile $wan] 200 | } 201 | :if (([:pick [/interface get value-name=type $wan] 0 [:find [/interface get value-name=type $wan] "-"]]="sstp") and ([:typeof [:find [/ppp profile get value-name=on-up [/interface sstp-client get value-name=profile $wan]] "\$script wan=$wan"]]="nil")) do={ 202 | /ppp profile set on-up=([/ppp profile get value-name=on-up [/interface sstp-client get value-name=profile $wan]]."\n".$script) [/interface sstp-client get value-name=profile $wan] 203 | } 204 | } 205 | ## Add script to dhcp-client on up ('bound') 206 | :if (([:len [/ip dhcp-client find interface=$wan]]>0) and ([:typeof [:find [/ip dhcp-client get value-name=script [/ip dhcp-client find interface=$wan]] "\$script wan=$wan"]]="nil")) do={ 207 | /ip dhcp-client set script=("/tool netwatch remove [/tool netwatch find comment=$wan]\n:if ([/ip dhcp-client get value-name=status [/ip dhcp-client find interface=$wan]]=\"bound\") do={\n :delay 5m\n :local script [:parse [/system script get wanmonitor source]]\n \$script wan=$wan hosts=$[:tostr $hosts]\n\n}") [/ip dhcp-client find interface=$wan] 208 | } 209 | } 210 | 211 | ## Create netwatch 212 | :local addNetwatch do={ 213 | :local ondown (":local script [:parse [/system script get wanmonitor source]]\n\$script wan=$wan hosts=".[:tostr $hosts]."\n\n"); 214 | :if ($watch!="0.0.0.0") do={ 215 | # Create netwatch per hosts, if not exists 216 | :if ([:len [/tool netwatch find where host=$watch]]=0) do={ 217 | /tool netwatch add host=$watch down-script=$ondown comment=$wan 218 | /tool netwatch set down-script=("/tool netwatch remove ".[/tool netwatch find where host=$watch]."\n\n".[/tool netwatch get value-name=down-script [/tool netwatch find where host=$watch]]) [/tool netwatch find where host=$watch] 219 | :log info ("'$watch' netwatch has been created by script.") 220 | } else={ 221 | # Set netwatch self remove, if not exists 222 | :if ([:typeof [:find [/tool netwatch get value-name="down-script" [/tool netwatch find host=$watch]] ("/tool netwatch remove ".[/tool netwatch find where host=$watch])]]="nil") do={ 223 | /tool netwatch set down-script=("/tool netwatch remove ".[/tool netwatch find where host=$watch]."\n".[/tool netwatch get value-name=down-script [/tool netwatch find where host=$watch]]) comment=("internet access via '$wan' enabled from ".[/system clock get time]." ".[/system clock get date]) [/tool netwatch find where host=$watch] 224 | } 225 | # Set append on-down event (run script), if 'wanmonitor' not exists 226 | :if ([:typeof [:find [/tool netwatch get value-name="down-script" [/tool netwatch find host=$watch]] "wanmonitor"]]="nil") do={ 227 | /tool netwatch set down-script=($ondown.[/tool netwatch get value-name="down-script" [/tool netwatch find host=$watch]]) [/tool netwatch find host=$watch]; 228 | } 229 | :log info ("'$watch' netwatch has been updated by script."); 230 | } 231 | # Set log 'error' when host is down 232 | :if ([:typeof [:find [/tool netwatch get value-name="down-script" [/tool netwatch find host=$watch]] ("/log error \"'$wan' was down.\"\n")]]="nil") do={ 233 | /tool netwatch set down-script=(("/log error \"'$wan' was down.\"\n").[/tool netwatch get value-name="down-script" [/tool netwatch find host=$watch]]) [/tool netwatch find host=$watch]; 234 | } 235 | } 236 | } 237 | 238 | ## Add scheduler 239 | :local AddScheduler do={ 240 | :local schname [:tostr $1] 241 | :local schcode [:tostr $2] 242 | :local schtime [:tonum $3] 243 | :if ([:len $3]=0) do={ 244 | :set $schtime 3600 245 | } 246 | :if ([:len [/system scheduler find name=$schname]]=0) do={ 247 | :log info ("scheduler '$schname' has been created and set to ".($schtime/60)."minutes"); 248 | /system scheduler add interval=$schtime on-event=$schcode comment=("recheck '$schname' for internet access every ".($schtime/60)." minutes.") name=$schname 249 | } else={ 250 | :if ([:typeof [:find [/system scheduler get value-name="on-event" [/system scheduler find where name=$schname]] $schcode]]="nil") do={ 251 | /system scheduler set interval=$schtime on-event=([/system scheduler get value-name=on-event $schname].$schcode) [/system scheduler find where name=$schname] 252 | :log info ("scheduler '$schname' has been updated and set to ".($schtime/60)."minutes"); 253 | } 254 | } 255 | } 256 | 257 | ## Add PPP script on up and DHCP Client script on up 258 | $onConnected wan=$Wan hosts=$Hosts 259 | 260 | ## Check if interface exists, bound and enabled 261 | :if ((([:len [/interface find where name=$Wan]]>0) and ([/interface get value-name=running [/interface find name=$Wan]]=true) and ([/interface get value-name="disabled" $Wan]=false) and ([:len [/ip address find interface=$Wan]]>0)) and (([:len [/ip dhcp-client find interface=$Wan]]=0) or ([/ip dhcp-client get value-name=status [/ip dhcp-client find interface=$Wan]]="bound"))) do={ 262 | ## Add IP routes rules to interface 263 | :foreach Host in=[:toarray $Hosts] do={ 264 | #Tempory write IP route to check specific connection 265 | /ip route add comment="tempory route for internet access checking..." distance=1 dst-address=$Host gateway=[$wmGateway wan=$Wan] 266 | /ip route add comment="tempory route for internet access checking..." distance=2 dst-address=$Host type=blackhole 267 | } 268 | :delay 750ms; 269 | ## Check interface's connection by ping to hosts 270 | :foreach Host in=[:toarray $Hosts] do={ 271 | :for Runtime from=1 to=$Retries do={ 272 | :if ([/ping $Host count=1]=0) do={ 273 | :set Failures ($Failures + 1); 274 | :log error "'$Wan' ping to $Host failed ($Runtime/$Retries)."; 275 | /beep frequency=80 length=20ms 276 | } else={ 277 | :log info "'$Wan' ping to $Host succeeded ($Runtime/$Retries)."; 278 | :set $WatchIp $Host; 279 | /beep frequency=20 length=80ms 280 | } 281 | :set Checks ($Checks + 1); 282 | :delay 500ms; 283 | } 284 | :delay 800ms; 285 | } 286 | } else={ 287 | :set Failures $Checks 288 | } 289 | ## Remove IP routes rules 290 | /ip route remove [/ip route find where comment="tempory route for internet access checking..."] 291 | :if ($Failures=$Checks) do={ 292 | :log error "internet access not available via '$Wan'!" 293 | $wmMode mode=disable wan=$Wan 294 | :if ([:len [/system scheduler find name=$Wan]]=0) do={ 295 | $telegram action=send chat=$TGID text=("Internet access *not available* via *'$Wan'*") 296 | } 297 | :if ([:len [/system scheduler find name=$Wan]]=0) do={ 298 | $wmReset wan=$Wan 299 | } 300 | $AddScheduler $Wan (":local script [:parse [/system script get wanmonitor source]]\n\$script wan=$Wan hosts=".[:tostr $Hosts]."\n") 300 301 | :return false; 302 | } else={ 303 | $wmMode mode=enable wan=$Wan 304 | ## Check currect status and update (comment) if necessary 305 | if ([:len [/tool netwatch find comment=$Wan]]=0) do={ 306 | :if ([:len [/system scheduler find name=$Wan]]>0) do={ 307 | /system scheduler remove [/system scheduler find name=$Wan] 308 | :log warning "'$Wan' scheduler has been removed" 309 | } 310 | :local publicip [$wmAddress wan=$Wan] 311 | $addNetwatch wan=$Wan hosts=$Hosts watch=$publicip 312 | :foreach script in=[:toarray $RUNONUP] do={ 313 | :if ([:len [/system script find name=$script]]>0) do={ 314 | :set script [:parse [/system script get $script source]] 315 | :if ([:find $WANS $Wan]=0) do={ 316 | $script 317 | } else={ 318 | $script interface=$Wan 319 | } 320 | } 321 | } 322 | $telegram action=send chat=$TGID text=("Internet access *available* via *'$Wan'* ($publicip)") 323 | } 324 | :return true 325 | } 326 | } 327 | 328 | :if ([:len $wan]>0) do={ 329 | :log info "Check for available internet access via '$wan' interface ..."; 330 | if ([$wmCheck $wan $hosts]=false) do={ 331 | ## Interface's connection failed 332 | :log error "'$wan' failed, No internet access available."; 333 | } else={ 334 | ## Interface's connection check succeed 335 | :log info ("'$wan' succeed, Internet access available."); 336 | } 337 | } else={ 338 | :local fconfig [:parse [/system script get wanmonitor.cfg source]] 339 | :local cfg [$fconfig] 340 | :local WANS ($cfg->"Interfaces") 341 | ## If interfaces not set manually, searching for clients/dialup connections (pppoe, l2tp, ppp, sstp) 342 | if ([:len $WANS]=0) do={ 343 | :foreach idn in=[/interface find where type="pppoe-out" and disabled=no or type="l2tp-out" and disabled=no or type="ppp-out" and disabled=no or type="sstp-out" and disabled=no] do={ 344 | :log info ([/interface get value-name=name $idn]." detected has internet interface"); 345 | if ([:len $WANS]=0) do={ 346 | :set $WANS ([/interface get value-name=name $idn]); 347 | } else={ 348 | :set $WANS ($WANS.",".[/interface get value-name=name $idn]); 349 | } 350 | } 351 | :foreach idn in=[/ip dhcp-client find where add-default-route="yes" and status="bound" and disabled=no] do={ 352 | :log info ([/interface get value-name=name $idn]." detected has internet interface"); 353 | :if ([/interface get value-name=type $idn]="ether") do={ 354 | if ([:len $WANS]=0) do={ 355 | :set $WANS ([/ip dhcp-client get value-name=interface $idn]); 356 | } else={ 357 | :set $WANS ($WANS.",".[/ip dhcp-client get value-name=interface $idn]); 358 | } 359 | } 360 | } 361 | } 362 | ## Check clients (ppp/pppoe/l2tp/sstp) 363 | :foreach wan in=[:toarray $WANS] do={ 364 | :set $wan [/interface get $wan name]; 365 | :if (([:len [/interface find name=$wan]]>0) and ([/interface get value-name="disabled" $wan]=false)) do={ 366 | :if ([:len [/tool netwatch find comment=$wan]]=0) do={ 367 | ## Check interface connection 368 | :log info "Check for available internet access via '$wan' interface ..."; 369 | if ([$wmCheck $wan]=false) do={ 370 | ## Interface's connection failed 371 | :log error "'$wan' failed, No internet access available."; 372 | } else={ 373 | ## Interface's connection check succeed 374 | :log info ("'$wan' succeed, Internet access available."); 375 | } 376 | } 377 | } else={ 378 | :log info ("'$wan' disabled, No internet access available."); 379 | } 380 | } 381 | } 382 | --------------------------------------------------------------------------------