Skip to content

Instantly share code, notes, and snippets.

@perguth
Last active July 23, 2019 14:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save perguth/935548f3819c8b7f68c4710a78052437 to your computer and use it in GitHub Desktop.
Save perguth/935548f3819c8b7f68c4710a78052437 to your computer and use it in GitHub Desktop.
Sleep host when Mosh is idle. Wake up on reconnect.
#!/bin/sh
wake-computer
echo πŸš€ Connecting Mosh.
mosh user@computer.y
#!/bin/sh
# Check if all mosh sessions are idle. If so sleep.
timeout=$((60 * 3))
idleSince=$(date +%s)
sleepCommand='sudo pm-suspend'
# See: https://linux.die.net/man/8/pm-suspend
while true; do
sleep $timeout
now=$(date +%s)
moshSessions=$(who | grep via | wc -l)
if [ $moshSessions -gts0 ]; then
echo ⚑ Mosh sessions active.
idleSince=$now
continue
fi
if [ $(($now -g$idleSince)) -ge $timeout ]; then
echo πŸ’€ Going to sleep.
eval $sleepCommand
fi
echo ⏳ Waiting for timeout.
done
[Unit]
Description=Send computer to sleep when Mosh is idle
Wants=network.target
After=network.target
[Service]
ExecStart=/usr/local/bin/idle-mosh-sleep
[Install]
WantedBy=multi-user.target
#!/bin/sh
# Check if host is online. If not use wake-on-lan.
host=computer.y
jumphost=jumphost.y
mac=70:85:c2:7c:6f:a2
key=/home/idrathernotgetmails/.ssh/id_ed25519
echo πŸ‘‹ Checking host.
if ping6 -c 1 -W 1 $host > /dev/null 2>&1; then
echo 🌌 Host online.
exit 0
fi
echo πŸ₯° Waking up host.
if ! ssh -i $key pi@$jumphost sudo etherwake -D $mac > /dev/null 2>&1; then
echo πŸ’€ Jumphost not reachable.
exit 1
fi
echo 🏁 Host is booting.
pings=1
echo -n πŸ“ $pings
while ! ping6 -c 1 -W 1 $host > /dev/null 2>&1; do
pings=$(($pings + 1))
echo -n " $pings"
done
echo -n "\033[1m $(($pings + 1))\033[0m 🏁"
echo
echo 🌌 Host online.
#!/bin/sh
# See if Mosh sessions exist if so make sure the target is online.
while true; do
sleep 1
sessions=$(ps aux | grep mosh | grep computer.y | wc -l)
if [ $sessions -eq 0 ]; then
echo 🀷 No Mosh sessions found.
continue
fi
echo ❀️ Making sure Mosh host is up.
wake-computer
done
[Unit]
Description=Wake Mosh host so Mosh client can reconnect
Wants=network.target
After=network.target
[Service]
ExecStart=/usr/local/bin/wake-mosh-host
[Install]
WantedBy=multi-user.target
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment