Advertisement
abrodkin

S20alwayson

Aug 9th, 2011
504
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 2.22 KB | None | 0 0
  1. #!/bin/sh
  2. #
  3. # DESCRIPTION
  4. # "alwayson" script for Asus wl500g router.
  5. #
  6. # Pings default gateway each INTERVAL seconds.
  7. # If ping fails tries to update dhcp parameters.
  8. #
  9. #
  10. # INSTRUCTIONS
  11. # Put script in "/usr/local/sbin"
  12. # Save flashfs:
  13. #     flashfs save && flashfs commit && flashfs enable
  14. # Reboot device
  15. #     reboot
  16.  
  17. # Log to stderr as well as the system log
  18. LOGGER_OPTIONS=-s
  19.  
  20. # Number of ping failures before interface restart
  21. ATTEMPTS=5
  22.  
  23. # Ping check interval set in seconds
  24. INTERVAL=3
  25.  
  26. # Ping timeout in seconds
  27. TIMEOUT=10
  28.  
  29. # Number of packets in ping
  30. PACKETS=1
  31.  
  32. # WAN interface name
  33. WAN=vlan1
  34.  
  35. logger $LOGGER_OPTIONS "Ping ($PACKETS packets, $TIMEOUT s timeout) default gateway each $INTERVAL s"
  36. logger $LOGGER_OPTIONS "    if $ATTEMPTS in row fail reset network connection"
  37.  
  38. # udhcpc command line
  39. UDHCPC="udhcpc -R -i $WAN -p /var/run/udhcpc0.pid -s /tmp/udhcpc.script"
  40.  
  41. # Counter of subsequential ping failures
  42. COUNTER=0
  43.  
  44. ME=`basename $0`
  45. RUNNING=`ps | awk '/'"$ME"'/ {++x}; END {print x+0}'`
  46. if [ "$RUNNING" -gt 3 ]; then
  47.    logger $LOGGER_OPTIONS "Another instance of \"$ME\" is running"
  48.    exit 1
  49. fi
  50.  
  51. while sleep $INTERVAL
  52. do
  53.    TARGET=`ip route | awk '/default via/ {print $3}'`
  54.    RET=`ping -w $TIMEOUT -c $PACKETS $TARGET 2> /dev/null | awk '/packets received/ {print $4}'`
  55.    # desktop ping shows number of received packets in 4-th place instead of 3-rd in busybox
  56.    # RET=`ping -c $PACKETS $TARGET 2> /dev/null | awk '/received/ {print $4}'`
  57.  
  58.    if [ -z $RET ]; then
  59.       RET=0
  60.    fi
  61.  
  62.    if [ $RET -ne $PACKETS ]; then
  63.       # PING FAILED
  64.       COUNTER=$((COUNTER+1))
  65.       echo "Ping failed. COUNTER: $COUNTER"
  66.    else
  67.       # PING SUCCEED
  68.       # enable to get messages on successful ping as well
  69.       # logger "Network is up via $TARGET"
  70.       echo "Network is up via $TARGET"
  71.       COUNTER=0
  72.    fi
  73.  
  74.    if [ "$COUNTER" -eq "$ATTEMPTS" ]; then
  75.       COUNTER=0
  76.       logger $LOGGER_OPTIONS "Ping failed $ATTEMPTS times, releasing IP address on $WAN"
  77.       # ensure udhcpc is not running
  78.       killall udhcpc 2> /dev/null
  79.       logger $LOGGER_OPTIONS "Renewing IP address: $WAN"
  80.       $UDHCPC
  81.       logger $LOGGER_OPTIONS "Waiting 10 s..."
  82.       sleep 10
  83.    fi
  84. done
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement