Skip to content

Instantly share code, notes, and snippets.

@kwanUm
Last active February 25, 2024 11:50
Show Gist options
  • Save kwanUm/da18ffc2819bf0a007129dbbe889f45d to your computer and use it in GitHub Desktop.
Save kwanUm/da18ffc2819bf0a007129dbbe889f45d to your computer and use it in GitHub Desktop.
Stop an idle GCP machine! This script assumes that you're connected through ssh with tmux to the machine, and when logging out usually the tmux session gets to the state detached. this script notices that and shuts down the machine
#!/bin/bash
# Initial timeout in seconds to wait before checking the SSH sessions
SLEEP_DURATION=300 # 5 minutes
# Additional wait time for the final check
FINAL_CHECK_DELAY=600 # 10 minutes
# Function to check tmux sessions
check_tmux_sessions() {
if tmux list-sessions &> /dev/null; then
# tmux is running, now check for detached sessions
detached_sessions=$(tmux list-sessions | grep -vc attached)
total_sessions=$(tmux list-sessions | wc -l)
if [ "$detached_sessions" -eq "$total_sessions" ]; then
# All tmux sessions are detached
return 0
else
# There are attached tmux sessions
return 1
fi
else
# tmux is not running
return 0
fi
}
# Main loop
while true; do
# Check for active SSH sessions excluding the script's own session
if check_tmux_sessions; then
echo "All tmux sessions are detached. Starting final check timer for $FINAL_CHECK_DELAY seconds."
sleep $FINAL_CHECK_DELAY
# Perform the check again after the delay
if check_tmux_sessions; then
echo "Final check passed. All tmux sessions are still detached. Initiating shutdown."
sudo shutdown -h now
exit
else
echo "Final check failed. There are attached tmux sessions now."
fi
else
echo "There are attached tmux sessions."
fi
sleep $SLEEP_DURATION
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment