So Jason paid me to write this script so everyone say thanks to his insane self for the script.
What he needed was a way to disable or enable his proxy NAT rules for his caching server depending on whether or not the service appears to be online.
He’s using a simple destination NAT rule that takes traffic destined for port 80 and redirects it to his proxy server(192.168.100.100).
/ip firewall nat
add action=dst-nat chain=dstnat disabled=no dst-port=80 protocol=tcp \
src-address=192.168.10.0/24 to-addresses=192.168.100.100 to-ports=3120
The flow is pretty simple:
– The router attempts to access traffic through the proxy.
– – If successful, enable the proxy nat rule.
– – If unsuccessful, disable the proxy nat rule.
If you check the packet flow diagram you will see that the router’s output chain can’t do destination natting. What you are forced to do is put in a static DNS entry that points traffic towards your proxy. In our case the URL we are going to redirect is www.JasonIsNuts.com.
Static DNS Entry
/ip dns static
add address=192.168.100.100 disabled=no name=www.jasonisnuts.com
To check for the proxy function we will use the fetch tool. The fetch tool works great as long as the service is working. As soon as the proxy fails, the fetch command tanks and kills your script. What we have to do to work around this limitation is to break the script into two parts: fetch script and check script.
The fetch script pulls a page through our proxy to the URL that is statically set to go through our proxy. We change the URL’s actual IP address of 192.168.100.10 to be the IP of the proxy server 192.168.100.100.
Fetch Script
/tool fetch url="http://www.JasonIsNuts.com/test.html" mode=http port=3128
The check script loops through all of the files looking to see if the test page successfully pulled, then it deletes the file if it exists, getting it ready for the next run.
Check Script
:local checkpage "test.html";
:local found "0";
:foreach i in=[/file find] do={
:local filename [/file get $i name];
if ( $filename = $checkpage) do={ :set found "1"; :log info "found"; }
}
:log info "$found";
if ( $found = "0" ) do={ :log info "Disable rule, service down"; /ip fire nat dis 0 } else={ :log info "Enable rule, service up"; /ip fire nat en 0; }
/file remove $checkpage;
The trick is to schedule the fetch script to run at whatever interval you like. You then schedule the check script to run at the same interval, only 10 seconds later. What this does is give the fetch script ample time to actually pull the page. If the fetch scripts pulls the file, the check script will enable the rule. If the fetch script fails and the file doesn’t exist, then the proxy NAT rule gets disabled.
If you enjoy the script, please drop me some feedback.

Leave a Reply