Skip to content

Instantly share code, notes, and snippets.

@lukebrowell
Forked from AstroTom/stop-if-inactive.sh
Created May 14, 2018 14:51
Show Gist options
  • Save lukebrowell/ae9971c987e9f93ed7441c9ec5161aef to your computer and use it in GitHub Desktop.
Save lukebrowell/ae9971c987e9f93ed7441c9ec5161aef 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