Last active
June 1, 2020 14:27
-
-
Save AvverbioPronome/51ab03faee394cfaa04b3600006a5f56 to your computer and use it in GitHub Desktop.
Very aggressive script to handle stuck network interfaces on a raspberry pi
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
ROUTER_IP=192.168.1.1 | |
COUNTER=/tmp/networkisdown | |
MAXCALLS_REBOOT=6 | |
WIFI_INTERFACES="wlan0 wlan1" | |
# Try the router, if it fails (ie. you are on an unknown network) try an external ip. | |
WIFI_TEST_CMD(){ | |
(ping -c 2 -w 2 $ROUTER_IP || ping -c 2 1.1.1.1 || ping -c 2 8.8.8.8) > /dev/null 2>&1 | |
} | |
TINC_TEST_CMD(){ | |
(ping -c 2 10.9.0.3 || ping -c 2 10.9.0.1 || ping -c 2 10.9.0.2) > /dev/null 2>&1 | |
} | |
error(){ >&2 echo "$@"; } | |
if [ ! -e "/run/systemd/system" ]; then | |
error "This script assumes systemd is the init system." | |
error "You can probably adapt it if it is not." | |
exit 99 | |
fi | |
# Check if wifi is up and try to reset, eventually reboot the machine. | |
if ! WIFI_TEST_CMD ; then | |
if [ -e "$COUNTER" ] && [ "$(stat -c %s $COUNTER)" -ge "$MAXCALLS_REBOOT" ]; then | |
echo "Network down, rebooting." | |
echo "$(date)" | |
systemctl reboot | |
else | |
printf . >> $COUNTER | |
systemctl daemon-reload | |
systemctl restart dhcpcd | |
fi | |
else | |
# Network is reachable, reset counter. | |
if [ -e "$COUNTER" ]; then | |
rm $COUNTER | |
fi | |
# Check wifi interfaces: | |
for INTERFACE in $WIFI_INTERFACES; do | |
if ! iw dev "$INTERFACE" link | grep -q Connected; then | |
ip link set "$INTERFACE" down | |
sleep 5 | |
ip link set "$INTERFACE" up | |
fi | |
done | |
# If wifi works, check if tinc is working, and restart it if not. | |
if ! TINC_TEST_CMD ; then | |
systemctl restart 'tinc*' | |
fi | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment