Shell – How to run a script when internet connection is about to get lost

ifconfigmobilenetwork-interfaceshell-scriptwvdial

I use wvdial (PPP dialer) with a SIM card modem and sometimes this connection is reset by server side. I would like to run a script which greps ifconfig to get a volume of data downloaded and stores it somewhere. Obviously it has to be done when connection is still alive, otherwise I get nothing, or a few seconds later a value for fresh connection, because wvdial is configured to immediately reconnect when connection is lost. Any idea?

Edit:

Of course I can grep output of ifconfig every second or two, but this is horrible workaround not even worth considering. The best scenario I can imagine is to somehow capture the signal which instructs ifconfig to "reset the counting" => suspend signal for a moment => run my script => unlock the signal. But maybe there are other possibilities which I'm not aware of like for example configure ifconfig itself to dump the previous result to a file if given interface disappears. Another option is to take output not from ifconfig by elsewhere. BTW, what is the input source for ifconfig?

Best Answer

you can write up your own shell script that logs exactly what you want, inside a while(1) loop with a sleep call at the end (or whatever length of sleep you want). Something like this:

function get_logname
  {
  echo `date +'%F-%H-%M-%S'`.log
  }

function am_online
  {
   ping -c 1 google.com  >/dev/null 2>&1
   echo $?
  }

function update_logfile
  {
  echo "YOUR DATA TO BE LOGGED" >> $1 
  }

  CUR_LOG=`get_logname`
  echo $CUR_LOG
  while [ 1 ]; do
        if [ "`am_online`" -eq 0 ]; then
           update_logfile $CUR_LOG
        else
           echo "we are offline!"
       CUR_LOG=`get_logname`
        fi

        sleep 1
  done

While you are online, it logs to your logfile (>> to append new data, > to rewrite the file to contain only the new data) every second. When you are offline it continually selects a new name for the next logfile, and logs nothing. When you go back online, it begins to log in a new logfile with the last selected logfile name, leaving the other logfile(s) intact.

This should do the trick for you. As with all code you find online, it is your responsibility to test it and make sure it does what you want and doesn't break anything. Specifically in this case, beware that logfiles can balloon in size pretty quickly, and that if you go offline often, you might end up with a bunch of logfiles.

Save as something like "my_internet_logging_script.sh" and run like:

sh my_internet_logging_script.sh

in the directory where you want your logfiles (or edit the script accordingly) to appear.

Related Question