Skip to content

Instantly share code, notes, and snippets.

@joemiller
Last active May 12, 2023 15:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joemiller/bc90882ef26c83e7f7e2493fd4bc3abb to your computer and use it in GitHub Desktop.
Save joemiller/bc90882ef26c83e7f7e2493fd4bc3abb to your computer and use it in GitHub Desktop.
bash script + systemd units for auto-shutting down an idle machine (no active ssh logins)
[Unit]
Description=Auto shutdown service
[Service]
Type=oneshot
ExecStart=/auto_shutdown.sh
#!/bin/bash
set -euo pipefail
set -x
# Set the threshold in seconds, 10 minutes = 600 seconds
#threshold=900
threshold=3600
# Check for active SSH connections
if ! active_connections=$(who | grep -E 'pts|tty' | grep -v tmux | wc -l); then
active_connections=0
fi
if [[ $active_connections -eq 0 ]]; then
if [[ ! -f /run/last_empty ]]; then
# Create a file with the current timestamp if no active connections and the file doesn't exist
date +%s > /run/last_empty
else
last_empty=$(cat /run/last_empty)
now=$(date +%s)
if [[ $((now - last_empty)) -ge $threshold ]]; then
# Shutdown the VM if the threshold is reached
rm /run/last_empty
shutdown -h now
fi
fi
else
# Remove the file if there are active connections
rm -f /run/last_empty
fi
[Unit]
Description=Auto shutdown timer
[Timer]
OnBootSec=5min
OnUnitActiveSec=1min
Unit=auto_shutdown.service
[Install]
WantedBy=timers.target
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment