Skip to content

Instantly share code, notes, and snippets.

@christianll9
Forked from why-not/stop-idle-azure-aws.py
Last active June 18, 2021 08:01
Show Gist options
  • Save christianll9/a70e5abe18e1565aa53b7a8066896728 to your computer and use it in GitHub Desktop.
Save christianll9/a70e5abe18e1565aa53b7a8066896728 to your computer and use it in GitHub Desktop.
Automatically Shutting Down Google Cloud VM (when idle AND no one is logged in via SSH)
# BASED on https://gist.github.com/why-not/18c5c0c00ee4cddf5ca176f770918639
# This is how the cron file should look like.
# PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/sn$
# * * * * * /home/script/stop-idle-gcloud.py > /tmp/user_error.log
## Watchout, for some reason cron files seem to require an extra new line at the end,
## consult this SO: https://askubuntu.com/questions/23009/why-crontab-scripts-are-not-working
## Also take care to setup a PATH variable for the cron explicitly. It doesn't see
## your regular PATH variable.
# ----
# Here is the code for stop-idle-gcloud.py
#!/usr/bin/env python
# make sure these commands run and do the proper thing.
# sudo netstat -tnpa | grep 'ESTABLISHED.*sshd'
# sudo poweroff
import re
import subprocess
THRESH = 75.0
def get_logged_in():
shellout = subprocess.Popen(['sudo', 'netstat', '-tnpa'], stdout=subprocess.PIPE)
shellout2 = subprocess.Popen(['grep', 'ESTABLISHED.*sshd'], stdin=shellout.stdout, stdout=subprocess.PIPE)
outlist = list(shellout2.stdout)
return len(outlist) == 0
def get_cpu_percent():
with open("/proc/loadavg", "r") as f:
cpu_list = f.readline().split()
cpu_percent = float(cpu_list[1])*100
return cpu_percent
def main():
# check to make sure there are no active
# ssh connections, meaning no humans
# are working on the machine,
# then go ahead and check
# the cpu usage in percent, if it falls
# below some threshold, send the command
# to shutdown the vm and deallocate it.
logged_in = get_logged_in()
cpu_percent = get_cpu_percent()
print ("cpu_percent: ", cpu_percent)
if logged_in:
if cpu_percent < THRESH:
print ("no one logged in, and vm is idle, stopping and deallocating.. ")
subprocess.run(['sudo', 'poweroff'])
else:
print("no one logged in, but vm is busy. leaving it alone..")
else:
print ("someone is logged in, leaving the vm alone.. ")
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment