1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

[v1.23] how to script automatic WAN DHCP release / renew?

Discussion in 'Tomato Firmware' started by luckman212, Apr 15, 2009.

  1. luckman212

    luckman212 LI Guru Member

    hi,
    I tried searching but couldn't find the thread I was looking for.
    I am looking for a script that i can run on my tomato that will ping every 10 or 30 seconds the WAN gateway. If it fails to ping, it should drop,release and then renew the WAN DHCP connection.

    lately my ISP has been dropping my connection, but tomato still shows 'connected'. I have no internet access until I go into the gui of my router and release/renew. SO I would like to automate this process if possible. I remember someone on here had a similar issue a while back and I think there was a script posted but for the life of me I can't find it.

    cheers to anyone who can help,
    thanks
     
  2. bogderpirat

    bogderpirat Network Guru Member

    `service wan restart` will reset the wan connection - i'm assuming it also re-does the dhcp-broadcasts.
     
  3. luckman212

    luckman212 LI Guru Member

    ok, I can give that a try.... can you help me with the part of the script that would ping the WAN IP every nn seconds and if it fails, execute the `service wan restart`?
     
  4. mstombs

    mstombs Network Guru Member

  5. dissident

    dissident LI Guru Member

    This might work. It's an init script for Tomato:

    Code:
    #####################################################
    # Beginning of stuff that NEEDS to go on the bottom #
    #####################################################
    
    # Perform DHCP renew and/or release/renew (and optional reboot) if WAN IP address pings fail
    
    ### Start of user settings ###
    # First IP address (not host name) to ping to check WAN accessibility.
    pingip1=xxx.xxx.xxx.xxx
    # Second IP address (not host name) to ping to check WAN accessibility.  Will be pinged only if first IP address ping fails.
    pingip2=xxx.xxx.xxx.xxx
    # Overall ping/DHCP release/DHCP renew loop delay. (Default: 60)
    delaysecs=60
    # Set to 0/1 to disable/enable router reboots. (Default: 1)
    enablereboot=1
    # Number of times to attempt DHCP release/renew before performing reboot. (Default: 60)
    relrencount=60
    # Number of consecutive successful pings required to enable rebootflag after each boot. (Default: 60)
    goodpingcount=240
    ### End of user settings ###
    
    # counter0 increments each time a ping of pingip1 or pingip2 succeeds.
    counter0=0
    # counter1 increments each time a DHCP renew is performed.
    counter1=0
    # counter2 increments each time a DHCP release/renew is performed.
    counter2=0
    # rebootflag is only turned on after a number of successful pings (based on counter0).
    rebootflag=0
    
    while [ true ] ; do
       if [ $counter0 -eq $goodpingcount ] ; then
          if [ $enablereboot -eq 1 ] ; then
             logger Automatic reboot after $relrencount DHCP release\/renew attempts enabled\. \($goodpingcount successful pings\.\)
             rebootflag=1
          fi
       fi
       /bin/sleep $delaysecs
       if ping -c 1 $pingip1 ; then
          if [ $counter1 -gt 0 ] ; then
             logger Ping of $pingip1 succeeded\.
          else
             if [ $counter2 -gt 0 ] ; then
                logger Ping of $pingip1 succeeded\.
             fi
          fi
          let counter0=counter0+1
          counter1=0
          counter2=0
          continue
       else
          if ping -c 1 $pingip2 ; then
             if [ $counter1 -gt 0 ] ; then
                logger Ping of $pingip2 succeeded\.
             else
                if [ $counter2 -gt 0 ] ; then
                   logger Ping of $pingip2 succeeded\.
                fi
             fi
             let counter0=counter0+1
             counter1=0
             counter2=0
             continue
          else
             counter0=0
             if [ $counter2 -eq $relrencount ] ; then
                if [ $rebootflag -eq 1 ] ; then
                   if [ $enablereboot -eq 1 ] ; then
                      logger Attempted DHCP release\/renew $counter2 times\. Performing reboot\.
                      /sbin/reboot
                      /bin/sleep 5
                   fi
                fi
             fi
             let counter1=counter1+1
             logger Ping of $pingip1 and $pingip2 failed\. Performing DHCP renew\. \(Attempt $counter1 since last successful ping\.\)
             /sbin/dhcpc-renew
             /bin/sleep 15
             if ping -c 1 $pingip1 ; then
                logger Ping of $pingip1 succeeded\.
                let counter0=counter0+1
                continue
             else
                if ping -c 1 $pingip2 ; then
                   logger Ping of $pingip2 succeeded\.
                   let counter0=counter0+1
                   continue
                else
                   let counter2=counter2+1
                   logger Ping of $pingip1 and $pingip2 failed\. Performing DHCP release\/renew\. \(Attempt $counter2 since last successful ping\.\)
                   /sbin/dhcpc-release
                   /bin/sleep 5
                   /sbin/dhcpc-renew
                fi
             fi
          fi
       fi
    done
     
  6. luckman212

    luckman212 LI Guru Member

    ok,
    thank you for the guidance.
    I have some issues now that I am too stupid to figure out.
    I have created the following script and placed it in my 'init' section:

    Code:
    sleep 5
    while [ `nvram get wan_get_dns` = "" ]; do
      logger waiting for external dns
    done
    wandns=`nvram get wan_get_dns | awk '{ print $1 }'`
    logger external dns is now $wandns
    logger entering main loop
    while [ true ]; do
      logger sleeping 10s
      sleep 10
      if ping -c 1 $wandns ; then
        logger $wandns is UP
      else
        logger $wandns is DOWN, requesting DHCP release/renew
        /sbin/dhcpc-release
        sleep 1
        /sbin/dhcpc-renew
        sleep 5
        wandns=`nvram get wan_get_dns | awk '{ print $1 }'`
        logger external dns is now $wandns
      fi
    done
    
    the problems is, the script doesn't work. I think specifically the method I'm using to test for the WAN ip is failing. Probably the syntax is no good. I wanted to use the `ip route` command to determine whether the wan state was "UP" or not- instead of `nvram get wan_get_dns` because I feel it would be more reliable (yes or no??) but the problem is that when my wan is up, ip route returns something like:
    Code:
    # ip route             
    172.31.255.0/24 dev br0  proto kernel  scope link  src 172.31.255.1 
    68.173.84.0/22 dev vlan1  proto kernel  scope link  src 68.173.87.40 
    127.0.0.0/8 dev lo  scope link 
    default via 68.173.84.1 dev vlan1 
    and when it's DOWN, it returns
    Code:
    # ip route
    192.168.100.0/24 dev vlan1  proto kernel  scope link  src 192.168.100.10 
    172.31.255.0/24 dev br0  proto kernel  scope link  src 172.31.255.1 
    127.0.0.0/8 dev lo  scope link 
    default via 192.168.100.1 dev vlan1 
    so either way there is a default gateway shown and I am not sure how I could determine if there was a "real" connection. I guess I could test if the default via` section is = 192.168.100.1 but I am not sure how to do that exactly. So basically I think I am 1/2 or 2/3 way there but need a little extra push in the right direction. :agree:
     
  7. mstombs

    mstombs Network Guru Member

    You have double quotes missing in the second line

    Code:
    while [ "`nvram get wan_get_dns`" = "" ]; do
    I'd also add a sleep inside that first wait loop.

    The trouble I've had with ping is that my ISP seems to drop ping packets when key routers are busy. I'm sure the kernel knows when it stops getting replies to normal traffic - I just don't know how to read that info.
     
  8. luckman212

    luckman212 LI Guru Member

    thanks for the help guys, with some tinkering I think I finally arrived with a working script. If anyone can see anything wrong with this or any way to make it more efficient I would love to hear !
    Code:
    while [ true ]; do
      while [ "`nvram get wan_get_dns`" = "" ]; do
        logger waiting for external dns
        /sbin/dhcpc-renew
        sleep 5
      done
      wandns=`nvram get wan_get_dns | awk '{ print $1 }'`
      if ping -c 5 -W 1 $wandns | grep "100% packet loss" ; then
        logger $wandns is DOWN, requesting DHCP release/renew
        /sbin/dhcpc-release
      else
        sleep 10
      fi
    done
    
     
  9. davipiero

    davipiero Addicted to LI Member

    Nice share... Let me keep tracking..
     
  10. BreeZier

    BreeZier Networkin' Nut Member

    @luckman212 Thanks for sharing (yet it already has been two years!), I actually used your script for a while now on tomatousb (v1.28.9054 MIPSR2-beta K26 USB vpn3.6)

    and it normally works flawlessly... until this morning where dns servers refused to answer to ping!

    Wouldn't it be more fool-proof to ping gateway instead of dns server?

    details below:

    The three DNS servers doesn't respond to ping (did it manually after removing script - got internet access) calling a renew which hangs.
    They all use port 53. The script logs that 24.200.241.37 is down and so tries to nenew but for some reason, can't and keeps logging "waiting for external dns"

    here are my ISP's DNS

    24.200.241.37:53, 24.201.245.77:53, 24.200.243.189:53

    Thanxs!
     
  11. luckman212

    luckman212 LI Guru Member

    Well yes normally that would be true, pinging the gateway is the "closest" device to your WAN port. However, sometimes you can have a case where gateway still responds and yet your internet is still down. That's why I chose to use DNS servers. It is usually safe to assume that if you have connectivity to your external DNS servers then your internet connectivity is working normally.

    If you want to use your wan gateway instead, the script is easy to modify: just change all the "$wandns" to "$wangw"
    and change all "wan_get_dns" to "wan_gateway_get". That should do what you want.
     
  12. BreeZier

    BreeZier Networkin' Nut Member

    Meanwhile I'm using a scheduler script:

    /bin/ping -c 1 8.8.8.8 > /dev/null; if [[ $? != 0 ]]; then /sbin/dhcpc-renew; logger "renewed dhcp lease"; fi

    which is working great until 8.8.8.8 is down one morning... ;)

    Edit: thanks for the answer, didn't see! Great info! Following your idea, how could I modify the script to ping 8.8.8.8 and/or 8.8.4.4, as I trust google servers more than my ISP's which may be blocking ping willingfully...
     
  13. luckman212

    luckman212 LI Guru Member

    maybe better to ping a series of IPs and only renew if ALL of them are down. Just an idea.
     
  14. BreeZier

    BreeZier Networkin' Nut Member

  15. roadkill

    roadkill Super Moderator Staff Member Member

    I think Administration -> Scheduler -> Reconnect is the simple method

     
  16. yudouxie

    yudouxie Reformed Router Member

    mark.
    I need this script.
     
  17. Xruptor

    Xruptor Connected Client Member

    I know this is an old thread but I wanted to put in my version of the script :)

    This version of the code from above uses the static DNS address that is entered in Tomato. So lets say you have the GOOGLE DNS servers as static, it will use 8.8.8.8 for the pinging.

    Code:
    # http://www.linksysinfo.org/index.php?threads/v1-23-how-to-script-automatic-wan-dhcp-release-renew.29372/
    # modified by Xruptor to use wan_dns instead of get_wan_dns.  This will return the static DNS instead of Modem
    # static dns should be 8.8.8.8
    
    while [ true ]; do
      while [ "`nvram get wan_get_dns`" = "" ]; do
        logger waiting for external dns
        /sbin/dhcpc-renew
        sleep 5
      done
      wandns=`nvram get wan_dns | awk '{ print $1 }'`
      if ping -c 5 -W 1 $wandns | grep "100% packet loss" ; then
        logger $wandns is DOWN, requesting DHCP release/renew
        /sbin/dhcpc-release
      else
        sleep 10
      fi
    done
     
    Last edited: Jun 18, 2015
  18. Xruptor

    Xruptor Connected Client Member

    Apparently certain modems won't do anything with the /dhcpc command. In these cases you may need to use udhcpc instead. If the above code does not work for you, try this one instead.

    Code:
    # http://www.linksysinfo.org/index.php?threads/v1-23-how-to-script-automatic-wan-dhcp-release-renew.29372/
    # modified by Xruptor to use wan_dns instead of get_wan_dns.  This will return the static DNS instead of Modem
    # static dns should be 8.8.8.8
    
    # cable modems require the SIGUSR1 and SIGUSR2 commands
    # https://stuff.mit.edu/afs/sipb/project/merakidev/src/openwrt-meraki/openwrt/build_mips/busybox-1.1.0/networking/udhcp/README.udhcpc
    
    while [ true ]; do
      while [ "`nvram get wan_get_dns`" = "" ]; do
        logger Renewing DHCP and waiting for external DNS
        killall -SIGUSR1 udhcpc
        sleep 10
      done
      wandns=`nvram get wan_dns | awk '{ print $1 }'`
      if ping -c 5 -W 1 $wandns | grep "100% packet loss" ; then
        logger $wandns is DOWN, requesting DHCP release/renew
        killall -SIGUSR2 udhcpc
      else
        sleep 10
      fi
    done
     
  19. my_bey

    my_bey Connected Client Member


    I am on Shibby's Tomato Firmware 1.28.0000 -130 K26ARM USB AIO-64K loaded on R7000.
    I created a schedule to reconnect every day at 4AM. And every morning, I found my internet was disconnected. I had to click on "Release, then renew" buttons on the Status page to make internet working. Scheduled "Reconnect" disables my internet connection.

    I also had also the following script in the Custom scheduler which is running every minute of every day as an independent check:

    Code:
    /bin/ping -c 1 8.8.8.8 > /dev/null; if [[ $? != 0 ]]; then /bin/ping -c 1 8.8.4.4 > /dev/null; if [[ $? != 0 ]]; then /sbin/dhcpc-renew; logger "renewed dhcp lease"; fi;fi
    Unfortunately, this did not fix the internet disconnection when happened.
    When the internet seemed to be disconnected, I performed /bin/ping -c 1 8.8.8.8 from the putty. Ping is responding.
    When I issue /bin/ping -c 1 google.com, from putty, Ping is not responding.
    When I issue /sbin/dhcpc-renew command from Putty, I still do not get internet connection.
    When I issue service wan restart command from Putty, I get connection.

    So, I changed the scheduled script as follows to make the connection work, in case it is lost:

    Code:
    /bin/ping -c 1 google.com > /dev/null; if [[ $? != 0 ]]; then /bin/ping -c 1 yahoo.com > /dev/null; if [[ $? != 0 ]]; then "service wan restart"; logger "WAN Restarted"; fi;fi
    In the meantime, for now, I unchecked Administration -> Scheduler -> Reconnect to prevent losing internet connectivity because it is causing me losing internet connectivity! Is there something I missed here? Or is this behavior repeatable by anyone else?
     
  20. TomatoUSB

    TomatoUSB New Member Member

    Where do I add this script "iptables -I FORWARD -i br0 -o `nvram get wan_iface` -j DROP"? It is suppose to kill my VPN when it's down.
     
  21. my_bey

    my_bey Connected Client Member

    I think you can add that script to Administration, Scripts, Firewall tab. I cannot answer your question about VPN.
     
  22. KyleS

    KyleS Networkin' Nut Member

    Careful with pinging google constantly. In the past, they would mark your address as looking suspicious and you'd hit extra captcha's.
     
    AndreDVJ likes this.
  23. Xruptor

    Xruptor Connected Client Member

    I've changed the way my personal script works. It's a modified version of one that I found. It will now ping multiple IP's just in case. Starting with the modem gateway. This is the closest device and least likely to give you issues when pinging. The fallback is google DNS servers so this should help with "suspecious" ip being blocked by google.

    Put this script in your Administration -> Scripts -> Init
    Restart your router for changes to take affect.

    Code:
    # http://tomatousb.org/forum/t-454177/wan-dhcp-issues
    # modified by Xruptor
    
    # No of times to check each host before trying next
    TRIES=1
    # How often to check in seconds if OK
    TCHECK=60
    # How long to wait if all hosts fail
    TFAIL=5
    # How many fails before restarting dhcp
    NFAIL=3
    
    # defaults don't touch
    GATEWAY="0.0.0.0"
    HSTS="8.8.8.8 8.8.4.4"
    chk=0
    dn=0
    
    CHK(){
        cnt=0
        chk=0
        while [ $cnt -lt $TRIES ]; do
             if /bin/ping -c 1 -W 5 -w 5 $@  >/dev/null; then
                chk=1
                break
            else
                let cnt=cnt+1
            fi
        done
    }
    
    gatewayip() {
        dn=0
        GATEWAY=`nvram get wan_gateway`
        if [ -z "$GATEWAY" ]; then
            GATEWAY="0.0.0.0"
        fi
        if [ $GATEWAY = "0.0.0.0" ]; then
            dn=3
        fi
            HSTS="$GATEWAY 8.8.8.8 8.8.4.4"
    }
    
    while [ true ]; do
    
        gatewayip
       
        while [ $dn -lt $NFAIL ]; do
            for h in $HSTS; do
                UP=0;
                CHK $h
                if [ $chk -gt 0 ]; then
                    UP=1
                    break
                else
                    logger -p INFO -t CHECKWAN "WAN Ping check failed on host $h"
                fi
            done
    
            if [ $UP -gt 0 ]; then
                dn=0
                sleep $TCHECK
            else
                let dn=dn+1
                logger -p INFO -t CHECKWAN "WAN Check Failure # $dn"
                sleep $TFAIL
            fi
        done
       
        logger -p INFO -t CHECKWAN "Releasing DHCP for forced renewal"
        killall -SIGUSR2 udhcpc
        sleep 8
        GATEWAY="0.0.0.0"
       
        logger -p INFO -t CHECKWAN "Attempting to force a continous renew of the DHCP."
        while [ $GATEWAY = "0.0.0.0" ] || [ -z "`nvram get wan_get_dns`" ]; do
            killall -SIGUSR1 udhcpc
            sleep 10
            gatewayip
        done
        logger -p INFO -t CHECKWAN "WAN DHCP has been renewed."
        sleep 10
       
    done
    
    
     
    Last edited: Jun 30, 2015
  24. AndreDVJ

    AndreDVJ Addicted to LI Member

    DNS servers may come down. If they come down, DHCP renew won't do anything as it's very unlikely that DNS servers will change.

    You should instead take advantage of option "Use received DNS with user-entered DNS" where you can use per example Google DNS servers along with your ISP ones.

    You can validate that dnsmasq will resolve against all these DNS servers by looking at /etc/resolv.dnsmasq.

    Then you can play with either --strict-order or --all-servers and see how them would suit you. Please see dnsmasq man page.

    I have writen another wan check script for my own usage as well. It's more focused on ISP gateway because if I don't have ISP's gateway working, then I have nothing. I also avoid pinging servers when nothing is working so a single variable controls how the whole script behaves.

    Another point is that when signal comes down for cable modems (at least five different ones I owned so far) the gateway IP falls back to cable modem's own (192.168.100.1) and I don't want to check that IP.

    Finally, if Tomato does not have a good connection to ISP's gateway, the gateway goes to at 0.0.0.0, so if I see such IP address I just assume everything is down, and I keep trying to renew DHCP lease.

    You can check my script below, written for the needs I described above. It could give an idea or two.

    Code:
    #!/bin/sh
    
    # Written by AndreDVJ for Tomato Firmware
    # http://linksysinfo.org/
    #
    # Description of the variables
    #
    # GATEWAY = WAN Gateway IP address coming from `nvram get wan_gateway`
    # INTERVAL = How long will wait (sleep) between commands
    # STATUS = 0 good, 1 missed ping, 2 missed second ping, 3 gateway is down
    
    GATEWAY="0.0.0.0"
    INTERVAL="0"
    STATUS="0"
    
    interval() {
        sleep $INTERVAL
    }
    
    gatewayip() {
        if [ `nvram get wan_gateway` != "192.168.100.1" ]; then
            GATEWAY=`nvram get wan_gateway`
        fi
        if [ $GATEWAY == "0.0.0.0" ]; then
            STATUS=3
        fi
    }
    
    checkping() {
        if [ "$STATUS" -lt 2 ]; then
            if ping -c 1 $GATEWAY > /dev/null; then
                INTERVAL=60
                STATUS=0
            else
                STATUS=$((STATUS + 1))
                INTERVAL=10
            fi
        fi
    }
    
    report() {
    #    [ "$STATUS" == 0 ] && logger "$GATEWAY is up..."
        [ "$STATUS" == 1 ] && logger "$GATEWAY missed ping..."
        [ "$STATUS" == 2 ] && logger "$GATEWAY seems down, missed another ping, refreshing DHCP..."
        [ "$STATUS" == 3 ] && logger "WAN down, refreshing DHCP..."
    }
    
    # Specific for Netgear WNR3500Lv2
    ledaoss() {
        [ "$STATUS" == 0 ] && led aoss on
        [ "$STATUS" -gt 1 ] && led aoss off
    }
    
    refreshdhcp() {
        if [ "$STATUS" -gt 1 ]; then
            killall -SIGUSR2 udhcpc
            sleep 2
            killall -SIGUSR1 udhcpc
            STATUS=0
            GATEWAY="0.0.0.0"
            INTERVAL=60
        fi
    }
    
    while :; do
        interval
        gatewayip
        checkping
        report
        ledaoss        # Specific for Netgear WNR3500Lv2
        refreshdhcp
    done
    
     
    Last edited: Jun 27, 2015
  25. my_bey

    my_bey Connected Client Member

    This morning, I incorporated AndreDVJ script into my router under INIT tab, rebooted the router. Everything was working. I left home, when I came back in the afternoon, after a few hours later, I found out that we have no internet connection at all devices at home. My Browsers were not returning internet web pages.

    I logged in to the router and to Putty. From Putty, I pinged google.com, 8.8.8.8, yahoo.com, and every one of them replied.

    Then, I used my PC's DOS command and pinged the same sites, and none of them responded!!!

    Router seems to be accessing internet but not allowing my devices to access the internet? How is this possible?

    I used these 2 commands in AndreDVJ script from putty:
    killall -SIGUSR2 udhcpc
    killall -SIGUSR1 udhcpc
    then my PC got the Internet connection again.
     
  26. AndreDVJ

    AndreDVJ Addicted to LI Member

    Not a clue, doesn't make much sense to me what happened. If router isn't the LAN's DNS server, please have it be. Tick checkbox for option "Use internal DNS" under "Advanced Settings/DHCP / DNS".

    Also, my script isn't really a generic one. To become more "generic", take out the logic which check against 192.168.100.1 IP address. Replace gatewayip() function with the code below:

    Code:
    gatewayip() {
         GATEWAY=`nvram get wan_gateway`
    
        if [ $GATEWAY == "0.0.0.0" ]; then
            STATUS=3
        fi
    }
     
  27. my_bey

    my_bey Connected Client Member

    AndreDVJ,

    Thanks for replying. I made the changes you recommended. By the way, 192.168.100.1 is my Cable Modem IP address. Also, the router is the LAN's DNS server.

    I am suspecting, anytime there is a scheduled "Reconnect" event, or a custom scheduled event that will issue "service wan restart" on my router, the behavior I explained above may happen. (Router can ping internet IPs, but PCs cannot ping those IPs from DOS command!!??). My understanding is, your script or the other ones mentioned above will help if the router cannot ping internet IP addresses.

    As a side note: led aoss on/off commands seems to be working for R7000.
     
  28. AndreDVJ

    AndreDVJ Addicted to LI Member

    You may revert the change, as router should not ping that address in any circumstances.

    EDIT: If you pull the coaxial cable (or have signal issues), router will get 192.168.100.1 as gateway address and script will be rendered useless. You need to test to verify if that scenario applies to you. In my case (NET Virtua + Cisco DPC3925), it does.

    Code:
    root@WNR3500Lv2:/tmp/home/root# nvram get wan_gateway
    179.159.200.1
    root@WNR3500Lv2:/tmp/home/root# killall -SIGUSR2 udhcpc
    root@WNR3500Lv2:/tmp/home/root#         sleep 2
    root@WNR3500Lv2:/tmp/home/root# killall -SIGUSR1 udhcpc
    root@WNR3500Lv2:/tmp/home/root# nvram get wan_gateway
    0.0.0.0
    root@WNR3500Lv2:/tmp/home/root# nvram get wan_gateway
    0.0.0.0
    root@WNR3500Lv2:/tmp/home/root# killall -SIGUSR1 udhcpc
    root@WNR3500Lv2:/tmp/home/root# nvram get wan_gateway
    192.168.100.1
    
    Well, I'll try to tell some story on why I made this script.

    Until few weeks ago I was using sort of script based on that one here: http://www.linksysinfo.org/index.php?threads/custom-tomato-script.19525/#post-89529

    It's pretty awful to be honest and I knew that, but I was facing some issues with my cable modem and I had to step up and write one from scratch.

    My requirement was to not spawn ping commands if I had no gateway address because if you ping 0.0.0.0, it's going to ping your loopback interface (127.0.0.1)

    Code:
    root@WNR3500Lv2:/tmp/home/root# ping -c 4 0.0.0.0
    PING 0.0.0.0 (0.0.0.0): 56 data bytes
    64 bytes from 127.0.0.1: seq=0 ttl=64 time=0.472 ms
    64 bytes from 127.0.0.1: seq=1 ttl=64 time=0.440 ms
    64 bytes from 127.0.0.1: seq=2 ttl=64 time=0.406 ms
    64 bytes from 127.0.0.1: seq=3 ttl=64 time=0.410 ms
    
    --- 0.0.0.0 ping statistics ---
    4 packets transmitted, 4 packets received, 0% packet loss
    round-trip min/avg/max = 0.406/0.432/0.472 ms
    
    So if ISP honored the release/renew commands (and I don't trust my ISP enough, that's the reason I kept the 2-second interval between commands), nvram get wan_gateway is going to fetch a good IP address as gateway from my ISP.

    If not, keep issuing release/renew commands until I get a good one.

    If I have a gateway, I check connectivity against that gateway address.
    If misses ping, two unsuccessful ping attempts will increment STATUS variable and will make refreshdhcp() function kick in. (status variable greater than 1).

    Finally, AOSS LED on my router will tell me what's going on based on STATUS variable. Reporting functions the same way.



    I also forgot to mention that, depending on where you make changes, init/firewall/wanup scripts will kick off again. I reported here: http://linksysinfo.org/index.php?th...-settings-spawn-wanup-and-init-scripts.71057/

    What I did to overcome these issues, is to have some sort of control to abort script if a given "dummy" file is found. If not found, launch the script (from somewhere else in my USB stick). That's what I use as my init script:

    Code:
    DUMMY=/tmp/home/root/init.dummy
    
    if [ -f $DUMMY ]
    then
        exit
    else
        while [ ! -e /mnt/storage ]
        do
            sleep 1
        done
    
        /mnt/storage/scripts/init.sh &
        touch $DUMMY
    fi
    
    
     
    Last edited: Jun 29, 2015
  29. AndreDVJ

    AndreDVJ Addicted to LI Member

    I made some enhancements on my script...

    DNS servers do come down, and for some reason if dnsmasq forwards a request from a LAN client to a bad DNS server, you can't browse internet. This can happen with any LAN client, and unfortunately dnsmasq does not test DNS servers to tell whether it's up or down.

    This scenario happened with me twice and I had no idea what was going on, until I realized that my ISP gives a bad DNS server address through DHCP... Way to go NET Virtua...

    Since I give the router's IP address as DNS server for my LAN clients, a solution should come from the router and prevent DNS requests getting forwarded to that bad server.

    The good news is that, if you take out the bad DNS server from /etc/resolv.dnsmasq, dnsmasq will automatically poll the file for any changes and refresh automatically if there were changes, without the need to restarting the daemon or sending any signals.

    Also, they may come back up, and it's a good thing to add them back to /etc/resolv.dnsmasq else eventually you'll run out of DNS servers to forward requests from your LAN clients. I can tell that because while I was writing the script, I noticed that even good DNS servers can come down and all I had left on /etc/resolv.dnsmasq was the Google ones.

    Eventually if you run out of DNS servers, you need to refresh your DHCP to see if you can acquire new set of IP addresses from your ISP.

    With all that in mind, I created a function that removes the bad DNS server address from /etc/resolv.dnsmasq and have it written to another file. If that another file has an IP address, we're going to check if it's back up.

    If it's back up, it'll get added back to /etc/resolv.dnsmasq and we let the daemon do its job which is poll the file and refresh. Otherwise it's going to stay there.

    I tested these scenarios and the script is working as intended. Remember that I have a cable modem, so I can't tell how this is going to work for ADSL users.

    If someone is using my script, have my updated version to be pasted straight on the Init script.

    There's some code to prevent this script being executed more than once if an event kicks off Init/Firewall/WAN Up scripts. You may edit to suit your needs or take it out.

    This script can be too big to have it stored on NVRAM. Please take out comments, extra spaces, take out functions/statements.

    I appreciate any feedback. I spent a lot of time covering all of the scenarios and trying to come with a proper script despite not being a good programmer. Not to mention that my ISP sucks. Since cable modem stuff are fairly standardized across ISP's, it may work with all of them.

    Code:
    if [ -f /tmp/home/root/init.dummy ]
    then
        exit
    else
        touch /tmp/home/root/init.dummy
    fi
    
    # Written by AndreDVJ for Tomato Firmware
    # http://linksysinfo.org/
    #
    # Description of the variables
    #
    # GATEWAY = WAN Gateway IP address coming from `nvram get wan_gateway`
    # INTERVAL = How long will wait (sleep) between commands
    # STATUS = 0 good, 1 missed ping, 2 missed second ping, 3 gateway is down, 4 DNS servers not working
    
    GATEWAY="0.0.0.0"
    INTERVAL=0
    STATUS=0
    
    interval() {
        sleep $INTERVAL
    }
    
    gatewayip() {
        if [ `nvram get wan_gateway` != "192.168.100.1" ]; then
            GATEWAY=`nvram get wan_gateway`
        fi
    
        if [ $GATEWAY == "0.0.0.0" ]; then
            STATUS=3
        fi
    }
    
    checkping() {
        if [ "$STATUS" -lt 2 ]; then
            if ping -w 1 $GATEWAY > /dev/null; then
                INTERVAL=60
                STATUS=0
            else
                STATUS=$((STATUS + 1))
                INTERVAL=10
            fi
        fi
    }
    
    checkdns() {
        if [ "$STATUS" -lt 2 ]; then
            if [ -s /etc/resolv.dnsmasq ]; then
                for DNSIP in $(cat /etc/resolv.dnsmasq | awk '{print $2}')
                do
                    if ping -w 2 $DNSIP > /dev/null; then
                        :
                    else
                        logger "DNS server $DNSIP is down, removing from /etc/resolv.dnsmasq..."
                        sed -i '/'$DNSIP'/d' /etc/resolv.dnsmasq
                        echo "$DNSIP" >> /etc/resolv.down
                    fi
                done
            fi
    
            if [ -s /etc/resolv.down ]; then
                sort -u /etc/resolv.down -o /etc/resolv.down
                for DNSDOWN in $(cat /etc/resolv.down)
                do
                    if ping -w 2 $DNSDOWN > /dev/null; then
                        logger "DNS server $DNSDOWN is back up..."
                        sed -i '/'$DNSDOWN'/d' /etc/resolv.down
                        echo "nameserver $DNSDOWN" >> /etc/resolv.dnsmasq
                    fi
                done
            fi
    
            if [ -s /etc/resolv.dnsmasq ]; then
                :
            else
                STATUS=4
                rm /etc/resolv.down
            fi
        fi
    }
    
    report() {
    #    [ "$STATUS" == 0 ] && logger "$GATEWAY is up..."
        [ "$STATUS" == 1 ] && logger "$GATEWAY missed ping..."
        [ "$STATUS" == 2 ] && logger "$GATEWAY seems down, missed another ping, refreshing DHCP..."
        [ "$STATUS" == 3 ] && logger "WAN down, refreshing DHCP..."
        [ "$STATUS" == 4 ] && logger "No DNS servers are available, refreshing DHCP..."
    }
    
    # Specific for Netgear WNR3500Lv2
    ledaoss() {
        [ "$STATUS" == 0 ] && led aoss on
        [ "$STATUS" -gt 1 ] && led aoss off
    }
    
    refreshdhcp() {
        if [ "$STATUS" -gt 1 ]; then
            killall -SIGUSR2 udhcpc
            sleep 2
            killall -SIGUSR1 udhcpc
            STATUS=0
            GATEWAY="0.0.0.0"
            INTERVAL=60
        fi
    }
    
    while :
    do
        interval
        gatewayip
        checkping
        checkdns
        report
        ledaoss        # Specific for Netgear WNR3500Lv2
        refreshdhcp
    done
    
     
    Last edited: Jul 13, 2015
  30. my_bey

    my_bey Connected Client Member

    AndreDVJ,

    Thanks for the improved script. I will be using it.

    Once in a while, I am still experiencing the odd phenomenon I listed in a few posts back, i.e., While the Router is able to ping internet IPs, other devices on LAN cannot access the internet. I have to manually login to the router, then Renew the DHCP for everything to work again.

    EDIT:
    Is there a way to perform a ping test from the router as if it is coming from one of the LAN ports to be able to detect the condition I listed above? If so, your script can be improved further.

    EDIT 16 July 2015:
    Scheduling a Reconnect event from "Administration, Scheduler, Reconnect" or creating a custom Scheduler script which will execute "service wan restart" is causing me to lose internet connection (Not from router but from LAN devices). I am on Shibby's Tomato Firmware 1.28.0000 -130 K26ARM USB AIO-64K.
    Can someone test this if they observe the same phenomenon? I am wondering if there is there a bug somewhere in my system or is it the firmware code that needs to be looked at.
     
    Last edited: Jul 16, 2015
  31. AndreDVJ

    AndreDVJ Addicted to LI Member

    No way to have such test unfortunately.

    I believe I overlooked your setup, but "service wan restart" command will kill your internet connection. This may be useful for those with dynamic IP's like ADSL subscribers. If you have it enabled please disable it.
     
  32. my_bey

    my_bey Connected Client Member

    Hi AndreDVJ at al,

    A couple of days ago, I realized that we do not have internet connection again. First thing I did was to ping 8.8.8.8 from my PC , it did not ping. Then I SSH'd to my Router, did the same ping, it replied. PC is not able to reach internet but router could. I tried to see if the Cable Modem was OK. using Firefox, I tried to login to 192.168.100.1. Modem did not respond at all. At this stage, I rebooted the router by pulling the power cable for about 30 seconds and reapplying power. After that, everything started to work normally.

    I then searched if there is a way to reboot the Cable Modem via software and came across this website:
    http://aaron-kelley.net/blog/2012/0...r-cable-modem-when-the-internet-goes-missing/
    The post there dated: August 16, 2015 at 1:15 PM is mine.

    On the other hand, if the Cable Modem web server did not respond to Firefox, I am not sure if wget would be successful to get a response from it, and if possible reboot it.

    Even though I could not succeed rebooting my SB6183 Cable Modem via wget due to lack of my knowledge, maybe it could be possible.

    I thought, If it is possible to incorporate such a code in your script, that would be perfect.

    Your thoughts?

    Regards,
     
  33. AndreDVJ

    AndreDVJ Addicted to LI Member

    It could be many things. What happened with me a couple of times was that my main PC wasn't browsing internet and my cellphone was working just fine. Both were wireless clients and PC has an Intel 5100 card.

    Sometimes I suspect the routing table might mess up. It's been a while since the last time my ISP was giving grief and I believe getting rid of bad DNS server resolved my issues.

    The last thing I would do is to reboot the router. I would try few more devices hoping to isolate the issue and if I can't really figure out, then reboot.

    If the wget command could work through the router, gets past any security and reboot cable modem, the script should be easy enough to expand, though it's getting too big to stay as an init script you might clean up the verbiage.

    You can:
    1. Add a new variable with similar functionality as status,
    2. Then modify refreshdhcp function to increment that new variable
    3. Create a new function to check new variable value and if it's greater or equal than a given value, execute wget command to have the cable modem rebooted.
    4. Few things to reset variable value and wait until cable modem is rebooted.
    I can't do it for you because I have a Cisco cable modem / router in bridge mode and the only way to have it rebooted is by pulling off the cable.

    You can even resort to have the script reboot your router. It's a matter of adding new functions and call them.
     

Share This Page