Skip to content

Instantly share code, notes, and snippets.

@Jflick58
Created August 24, 2021 06:10
Show Gist options
  • Save Jflick58/1e8a4b7923d05574f88ae54a38ce80b8 to your computer and use it in GitHub Desktop.
Save Jflick58/1e8a4b7923d05574f88ae54a38ce80b8 to your computer and use it in GitHub Desktop.
Shutdown Idle EC2 instances after 5 minutes of no SSH activity
#crontab entry - replace your_user with your actual user name
#*/10 * * * * /home/your_user/idle_shutdown.sh > shutdown_logs.txt
#check for established SSH connections
SSH_CONNS=`netstat | grep ssh | grep ESTABLISHED`
#If None
if [ -z "$SSH_CONNS" ]
then
#wait 5 minutes and check again
echo "No SSH Connections. Checking again in 5 minutes"
sleep 5m
SSH_CONNS2=`netstat | grep ssh | grep ESTABLISHED`
#If still no SSH connections
if [ -z "$SSH_CONNS2" ]
then
#kill instance
/sbin/shutdown -h now
else
echo "Active SSH conncections established during waiting period"
fi
else
echo "Active SSH conncections"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment