For a self-contained solution that doesn't require setting up other services, and doesn't depend on usage metrics, set this script to run on a schedule:
#!/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 /home/ubuntu/dotfiles/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
To run this script every 5 minutes, shutting down the instance after 10 minutes of inactivity, add this entry to /etc/crontab
:
*/5 * * * * root /home/ubuntu/bin/shutdown-if-inactive
Change /home/ubuntu/bin
to the path where the script was saved.
This was tested on an EC2 instance running Ubuntu 20.04. See source.
This expands on @dmohr's answer.