Simple bash script to check and auto change gateway on failure - fedora linux

This script was tested on fedora 7, but my friend said it work on the other version of fedora too -- This script used if you have 2 gateway, 1 gateway as a main route and the other as a slave, and you want to set your router to automatically change the route or firewall when the main gateway is down (we are not talking about fail over or load balancing on this post). This is not a perfect script but it's working on my current router now.

First, you have to create 2 firewall scripts. First script will handle the main route and gateway while the 2nd is to handle the 2nd route and gateway. You can read my previous post about the easy way to generate firewall using easy firewall generator.

The script:

#checking the main gateway
if [ `/bin/ping -c 1 | grep 'packets transmitted' | awk {'print $6'}` = "100%" ]; then #the main gateway down, write it to log file
echo `date` "- Gateway timeout : main gateway" >> /var/log/gateway.log

#checking the 2nd gateway
if [ `/bin/ping -c 1 | grep 'packets transmitted' | awk {'print $6'}` = "100%" ]; then #the slave gateway down, write it to log file
echo `date` "- Gateway timeout : 2nd gateway" >> /var/log/gateway.log
echo `date` "- No gateway are up, will check again in the next 5 minutes" >> /var/log/gateway.log

#run the 2nd firewall script

#sucess changing route, write it to log file
echo `date` "- New route, GW :" >> /var/log/gateway.log

#run the main firewall (it is needed to recover first route after the gateway down)

#sucess runing the main firewall, write it to log file
echo `date` "- Main route, GW :" >> /var/log/gateway.log #


On above script, is assumed as your main gateway and is the 2nd gateway (slave). It will check the first gateway with ping to check if it still up or not. If the main gateway still up, it will write to a log file telling that the gateway is up and running. Note that it will execute the first firewall that handle the main gateway and route, it is useful to recover the main gateway after the it down and changed to the 2nd gateway.

If the main gateway down, the script will check the 2nd gateway. If all of the gateway down, the script will write to log file telling that there are no gateway can be used at that time. Otherwise if the 2nd gateway is up, it will execute the script that handling the 2nd route and gateway (that's why we need 2 firewall scripts).

Well, I'm not good in script explanation but you can read the comment on every line to see what was that line do. Don't forget to put the script into a crontab list and make it execute for every 5 minutes. Last, hope the script useful, it's useful for me actually, because our main gateway are down oftenly caused by source power problem. Good luck.