Skip to content

Instantly share code, notes, and snippets.

@toxinu
Created October 11, 2021 10:31
Show Gist options
  • Save toxinu/e8f84236544b2d28dedf71b75021e43b to your computer and use it in GitHub Desktop.
Save toxinu/e8f84236544b2d28dedf71b75021e43b to your computer and use it in GitHub Desktop.
Shutdown server if no ssh
#!/bin/bash
#
# Shuts down the host on inactivity.
#
# Designed to be executed as root from a cron job.
# It will power off on the 2nd consecutive run without an active ssh session.
# That prevents an undesirable shutdown when the machine was just started, or on a brief disconnect.
#
# To enable, add this entry to /etc/crontab:
# */5 * * * * root /usr/local/bin/shutdown-if-inactive
#
set -o nounset -o errexit -o pipefail
MARKER_FILE="/tmp/ssh-inactivity-flag"
STATUS=$(netstat | grep ssh | grep ESTABLISHED &>/dev/null && echo active || echo inactive)
if [ "$STATUS" == "inactive" ]; then
if [ -f "$MARKER_FILE" ]; then
echo "Powering off due to ssh inactivity."
poweroff # See https://unix.stackexchange.com/a/196014/56711
else
# Create a marker file so that it will shut down if still inactive on the next time this script runs.
touch "$MARKER_FILE"
fi
else
# Delete marker file if it exists
rm --force "$MARKER_FILE"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment