The following script will shut down an instance that hasn't had any SSH connections in a while. The debounce defaults to 300 seconds.
- Copy these files into your VM:
/usr/bin/auto-shutdown.py
:
#!/usr/bin/env python3
import json
import math
import os
import subprocess
from pathlib import Path
import time
from datetime import datetime
def main():
timeout = int(os.environ.get("IDLE_TIMEOUT", "600"))
interval = 60
idle_since = getBootTime()
while True:
out = subprocess.check_output("last -F | jc --last", shell=True)
for user in json.loads(out):
if user.get("logout", None) == "still logged in":
idle_since = max(idle_since, datetime.now().timestamp())
elif "logout_epoch" in user:
idle_since = max(idle_since, user["logout_epoch"])
idle = round(datetime.now().timestamp() - idle_since)
if idle > timeout:
print(f"Idle for {idle}s, shutting down...")
subprocess.check_call("shutdown now", shell=True)
else:
print(f"Idle for {idle}s, checking again in {interval}s...")
time.sleep(interval)
def getBootTime():
uptime = float(Path("/proc/uptime").read_text().split()[0])
return datetime.now().timestamp() - uptime
if __name__ == "__main__":
main()
/etc/systemd/system/auto-shutdown.service
:
[Unit]
Description=Auto-shutdown VM
[Service]
ExecStart=/usr/bin/auto-shutdown.py
Restart=always
Environment=PYTHONUNBUFFERED=true
[Install]
WantedBy=multi-user.target
-
pip3 install jc
and ifwhich jc
shows conda, thensudo ln -sf /opt/conda/bin/jc /usr/bin/jc
sudo chmod u+x /usr/bin/auto-shutdown.py
sudo systemctl daemon-reload
sudo systemctl enable auto-shutdown.service
sudo systemctl restart auto-shutdown
systemctl status auto-shutdown.service
Top comments (0)