Skip to content

Instantly share code, notes, and snippets.

@fawkesley
Last active May 17, 2017 23:05
Show Gist options
  • Save fawkesley/c4162f58455253e9c4e0f46f18f63358 to your computer and use it in GitHub Desktop.
Save fawkesley/c4162f58455253e9c4e0f46f18f63358 to your computer and use it in GitHub Desktop.
Raspberry Pi Wifi check / restart script
#!/bin/sh -eu
# Save this to /root/check_wifi.sh then run `sudo crontab -e` and paste the following line:
# * * * * * /root/check_wifi.sh >> /root/check_wifi.log
INTERFACE=wlan0
ROUTER_IP=192.168.0.1
# INTERNET_SITE_A=fake.example.com
# INTERNET_SITE_B=fake.example.com
INTERNET_SITE_A=www.bbc.co.uk
INTERNET_SITE_B=www.twitter.com
UNREACHABLE_FILE=/var/run/internet_unreachable
PATH=$PATH:/sbin:/bin
THIS_SCRIPT=$0
log() {
echo "$( date --rfc-3339=seconds): $1"
}
wifi_interface_is_down() {
if ifconfig ${INTERFACE} | grep -q "inet addr:" ; then
# WiFi is UP, so return nonzero "fail"
return 1
else
# WiFi is DOWN, so return "success" eg "yes, it's down"
return 0
fi
}
router_unreachable() {
if ping_failed ${ROUTER_IP}; then
return 0
else
return 1
fi
}
internet_unreachable() {
if ping_failed ${INTERNET_SITE_A}; then
if ping_failed ${INTERNET_SITE_B}; then
return 0 # unreachable
fi
fi
return 1
}
ping_failed() {
if ping -c 1 -W 5 $1 > /dev/null ; then
return 1
else
return 0
fi
}
create_unreachable_file() {
if [ ! -f "${UNREACHABLE_FILE}" ]; then
echo "Created by ${THIS_SCRIPT} at $(date)" > "${UNREACHABLE_FILE}"
fi
}
remove_unreachable_file() {
rm -f "${UNREACHABLE_FILE}"
}
attempt_restart_wifi_interface() {
ifdown --force ${INTERFACE}
ifup --force ${INTERFACE}
sleep 10
if wifi_interface_is_down; then
log "That didn't seem to work."
else
log "That worked!"
fi
}
reboot_if_unreachable_too_long() {
if test "$(find ${UNREACHABLE_FILE} -cmin +15)"; then
log "Internet unreachable for too long, rebooting."
remove_unreachable_file
reboot
fi
}
if wifi_interface_is_down; then
log "${INTERFACE} appears down, attempting reconnection."
ifconfig
attempt_restart_wifi_interface
fi
if router_unreachable; then
log "Router is unreachable: ${ROUTER_IP}"
ifconfig
fi
if internet_unreachable; then
log "Internet is unreachable."
echo "${UNREACHABLE_FILE}"
cat "${UNREACHABLE_FILE}"
create_unreachable_file
reboot_if_unreachable_too_long
else
remove_unreachable_file
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment