Skip to content

Instantly share code, notes, and snippets.

@itsthejb
Last active September 11, 2018 17:33
Show Gist options
  • Save itsthejb/890ac85e867b9d478b690a4fc26c7268 to your computer and use it in GitHub Desktop.
Save itsthejb/890ac85e867b9d478b690a4fc26c7268 to your computer and use it in GitHub Desktop.
Reboot server on no network
#!/bin/bash
RETRIES=3
SLEEP=60
TEST_HOST="google.com"
if [[ $EUID -ne 0 ]]; then
echo "This script must be run as root"
exit 1
fi
function testConnection() {
/bin/ping -q -w1 -c1 $TEST_HOST &>/dev/null
/bin/echo "$?"
}
function timeElapsed() {
/bin/echo $(( SECONDS - START ))
}
function onFailed() {
/bin/echo "Failed! Rebooting"
/usr/bin/sudo /sbin/shutdown -r -t 1
exit 1
}
START=$SECONDS
ONLINE=$(testConnection)
WAS_OFFLINE=0
while [ "$ONLINE" -ne 0 ]; do
if [ "$RETRIES" -le 0 ]; then
/bin/echo "Offline: failed after $(timeElapsed)s"
onFailed
else
/bin/echo "Offline: waiting ${SLEEP}s to try again ($(timeElapsed)s, ${RETRIES}x)"
WAS_OFFLINE=1
(( RETRIES-- ))
/bin/sleep $SLEEP
ONLINE=$(testConnection)
fi
done
if [ "$WAS_OFFLINE" -eq 1 ]; then
/bin/echo "Online: connection came back after $(timeElapsed)s, ${RETRIES}x"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment