Wednesday, June 25, 2014

pingcheck.sh: restore wlan connection

Another simple script I used on my Raspberry PI and now use on odroid. It is simple, ping based check of IP address availability.
It has been designed to restore wlan0 connection, as from time to time I get disconnected from my network.
During the time I've added few features, like pingcheck of default GW and pingcheck of other IP addresses and network notifications which will send popup to my desktop PC.

First I show the pingcheck.sh script, the brief description will follow afterwards.
#!/bin/bash
###########
# krisko 2014
# script for simple ping check of IP address
###########

LogFile=/var/log/pingcheck.log
DefGW="192.168.0.1"
IPList="88.212.8.8"
WiFiNet="KrisKo24"
INT="wlan0"

# send notification
notify() {
    echo $(date "+%Y-%m-%d %H:%M") [$1]: $2 >> $LogFile
    echo "pingcheck":"$1 $2" | curl telnet://172.16.0.2:2234 2>/dev/null
}

pingIP() {
    # packet loss; 0% is good, 100% is bad
    [ $(ping -c 2 $1 | egrep -o '[[:digit:]]{1,3}%') == "0%" ] || return 1
    return 0
}

# try to restore connection
restoreconn() {
    IP=$(ifconfig | grep -A1 $INT | grep inet | awk '{print $2}')
    [ -z ${IP} ] && { systemctl restart netctl@wlan0; notify "ERROR" "$INT restarted"; exit 0; }

    iwlist wlan0 scan | grep -qo "$WiFiNet" && systemctl restart netctl@wlan0 || { notify "FATAL" "$WiFiNet network not found"; exit 1; }
    pingIP "$IPAddr" || { notify "FATAL" "$IPAddr connection restore failed"; exit 1; }
    notify "SUCCESS" "$IPAddr connection was restored"
}

# # # BEGIN # # #

for IPAddr in $DefGW; do
    pingIP "$IPAddr" || { notify "ERROR" "default gw down"; restoreconn "$IPAddr"; }
done

for IPAddr in $IPList; do
    pingIP "$IPAddr" || notify "ERROR" "failed to ping $IPAddr"
done

##################
# ChangeLog/TODO #
##################
# 1.0.0 2014-03-31 Genesis
# 1.0.1 2014-04-01 Added support for IPList
# 1.0.2 2014-04-01 Added message sending to ircnotify
# 1.1.0 2014-05-11 Added restore connection functionality
# 1.1.1 2014-05-27 Added IP detection for $INT
# 1.1.2 2014-06-15 Using systemctl instead of netctl
##################

DefGW is the defaul GW IP address, if ping to this IP fails, the connection will be restored (systemctl restart netctl@wlan0). As you can see, I use netctl to handle my connections.
IPList is space separated list of IP addresses, each of which is sequentially pinged and in case the ping fails, notification is sent. This can be used as simple ping check of machines with notifications. For more advanced pingcheck monitoring see my Server availability monitoring post.
notify() function uses part of my ircnotify setup to popup messages.

The script runs each minute and checks all IP addresses. It is launched via systemd timer, but you can run in from crontab without any difficulties.

No comments:

Post a Comment