Last active
August 29, 2015 14:06
-
-
Save plesner/2086b62c4034e47785dd to your computer and use it in GitHub Desktop.
Sh script for connecting to a machine while pinging it with a wake-on-lan package in the background every minute
This file contains hidden or 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 | |
set -e | |
# How often to send wake-on-lan pokes. | |
POKE_INTERVAL_SECS=60 | |
# Mac address of the machine to poke. | |
MAC_ADDR=00:25:4b:a0:65:9c | |
# Host address to connect to. | |
HOSTNAME=ab00 | |
# When run as [mosh-mini.sh poke] it loops around indefinitely poking | |
# the machine. | |
if [ "$1" = "poke" ]; then | |
while true; do | |
wakeonlan $MAC_ADDR > /dev/null | |
sleep $POKE_INTERVAL_SECS | |
done | |
fi | |
# Spawn the poke job and record its PID. Be careful here -- if the | |
# recursive call should for some reason not park in the loop above | |
# this script effectively becomes a fork-bomb. This happened. | |
$0 poke & | |
POKE_PID=$! | |
# Ensure that the poke job is killed when this script exits. | |
cleanup_on_exit() { | |
# Silence kill since, depending on how the signals bounce, this may be called | |
# more than once. Also, the poke job may die before we exit. | |
kill $POKE_PID > /dev/null 2>&1 | |
} | |
# Do cleanup on normal exit and interrupt (ctrl-C). | |
trap cleanup_on_exit EXIT INT | |
# Wait for at least one successful ping before trying to | |
# connect. Waking up can take a while and mosh gives up quickly if the | |
# destination doesn't respond. | |
if ! ping -c1 $HOSTNAME > /dev/null; then | |
echo "Host is currently unavailable; waiting for it to appear." | |
while ! ping -c1 $HOSTNAME > /dev/null; do | |
true | |
done | |
fi | |
# Finally we've seen a successful ping to the machine. Mosh it! | |
mosh $HOSTNAME |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment