Script to restart network connection, if it fails

# cat check-network.sh

#!/bin/bash
# replace wlan0 with your device name
# as given by ip addr or ifconfig
while true 
do
    # keep checking if we have ip address and can ping outside  
    wifi_info=$(ip -4 -o addr  show wlan0 )
    ping -w 30 baidu.com
    #ping -w 10 google.com  # test bad case
    ping_result=$(echo $?)
    echo $ping_result
    
    while [ -n "$wifi_info" ] && [ $ping_result -eq 0 ];
    do
       sleep 180    # 180 sec = 3 minutes
       wifi_info=$(ip -4 -o addr  show wlan0 )
       ping -w 30 baidu.com
       #ping -w 10 google.com  # test bad case
       ping_result=$(echo $?)
       echo $ping_result
    done

    # We get here only if IP address is lost
    # which means we're off-line
    # restart wifi 
    nmcli radio wifi off
    sleep 10
    nmcli radio wifi on
    sleep 20  # wait that wifi restarts and connects
done

 

# crontab -l

...
# Run at the boot
@reboot /root/scripts/check-network.sh > /dev/null &
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s