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:
# 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
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
# Create a marker file so that it will shut down if still inactive on the next time this script runs.
# Delete marker file if it exists
rm --force "$MARKER_FILE"
To run this script every 5 minutes, shutting down the instance after 10 minutes of inactivity, add this entry to
*/5 * * * * root /home/ubuntu/bin/shutdown-if-inactive
/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.