Last active
August 20, 2018 17:46
-
-
Save AstroTom/855d90a096bd9717e0ab3c2bd0e1613f to your computer and use it in GitHub Desktop.
Shutdown EC2 instance after timeout if no one is connected via ssh
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 | |
# 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