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 &

Leave a comment