Skip to content

Instantly share code, notes, and snippets.

@AstroTom
Last active August 20, 2018 17:46
Show Gist options
  • Save AstroTom/855d90a096bd9717e0ab3c2bd0e1613f to your computer and use it in GitHub Desktop.
Save AstroTom/855d90a096bd9717e0ab3c2bd0e1613f to your computer and use it in GitHub Desktop.
Shutdown EC2 instance after timeout if no one is connected via ssh
#!/bin/bash
# based on AWS Cloud9
# shutdown ec2 if no ssh connections after 1/2 hour
# Add to cron to run every minute
# User needs sudo permission to run 'shutdown'
#
set -euo pipefail
SHUTDOWN_TIMEOUT=30 # minutes
if ! [[ $SHUTDOWN_TIMEOUT =~ ^[0-9]*$ ]]; then
echo "shutdown timeout is invalid"
exit 1
fi
is_shutting_down() {
pgrep shutdown >/dev/null
}
is_ssh_connected() {
netstat | grep ssh | grep ESTABLISHED >> /dev/null;
}
if is_shutting_down; then
if is_ssh_connected; then
sudo shutdown -c
fi
else
if ! is_ssh_connected; then
sudo shutdown -h $SHUTDOWN_TIMEOUT
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment