Last active
May 12, 2023 15:44
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[Unit] | |
Description=Auto shutdown service | |
[Service] | |
Type=oneshot | |
ExecStart=/auto_shutdown.sh |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[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