Skip to content

Instantly share code, notes, and snippets.

Last active April 13, 2023 21:34
  • Star 14 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Automatically Shutting Down and Deallocating an AZURE VM (when idle AND no one is logged in via SSH)
# 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/ > /tmp/user_error.log
## Watchout, for some reason cron files seem to require an extra new line at the end,
## consult this SO:
## 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
#!/usr/bin/env python
# make sure these commands run and do the proper thing.
# You might need to install azure cli:
# "sudo apt install azure-cli " in ubuntu.
# netstat -tnpa | grep 'ESTABLISHED.*sshd'
# az vm deallocate --name "myvmname" --resource-group "myvmresourcegroup"
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():
f = open("/proc/loadavg", "r")
cpu_list = f.readline().split()
cpu_percent = float(cpu_list[1])
return cpu_percent
# If you want to check how long a machine
# has been running and stop based on that.
def uptime():
with open('/proc/uptime', 'r') as f:
uptime_seconds = float(f.readline().split()[0])
return uptime_seconds
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.. ")['az', 'vm', 'deallocate', "--name", NAME, "--resource-group", RESOURCE_GROUP])
print("no one logged in, but vm is busy. leaving it alone..")
print ("someone is logged in, leaving the vm alone.. ")
if __name__ == '__main__':
Copy link

Thanks for sharing the script.
Can you please let me know where should we schedule and run this script since we are running the de-allocate command ?

Copy link

why-not commented Oct 4, 2019

@sagu94271 you can run the script inside the target vm itself, deallocation is not a problem as that is the final command we are running. Infact this script assumes that it is running inside the machine that needs to be shutdown when idle.

Copy link

Thanks for the Script.. Please let us know the changes or script for Windows Servers (Azure) to get de-allocated when no user is logged in for 30 mins etc.

Copy link

why-not commented Dec 12, 2019

@vengateshk You would simply modify the if condition to something that fits your needs. For eg. "if cpu_percent < THRESH: " can be changed to "if cpu_percent < THRESH && not logged_in():" and you run your cron job every hour, you can have the required effect of de-allocating when no one is logged in and the cpu is idle as well.

Copy link

import psutil is not needed

Copy link

why-not commented Jul 7, 2021

import psutil is not needed

fixed, thanks.

Copy link

chinniprakash commented Apr 13, 2023

Could you pls tell me how to modify this code to meet below requirement .
I have several windows azure vms . I need to make sure if no-one logins by remote desktop/any other way of login , I want to shutdown the in-active vms. ( Any way , I have your code for CPU, subprocesses ) etc

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment