Last active
January 26, 2020 21:48
-
-
Save rarecoil/344ff7ec4041338c4572d90e18429974 to your computer and use it in GitHub Desktop.
shutdown a box if it hasn't been logged into for a while
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import getpass | |
import re | |
import time | |
import subprocess | |
import sys | |
MIN_UPTIME = 1800 # 30 minutes of uptime required before autokilling | |
TIME_DELTA = 21600 # 6 hours of uptime max before autokilling | |
LOGIN_REGEXP=r"(\w+)\s+(pts/\d)\s+([\da-f:.]+)\s+([-+T:\d]+)\s+-?\s*(still logged in|[-+T:\d]+)" | |
def get_last_login(username=None): | |
"""Get the last login of the specified user. Defaults to the running user.""" | |
if username == None: | |
username = getpass.getuser() | |
proc = subprocess.run(["last", "--time-format", "iso", username], stdout=subprocess.PIPE, encoding="utf-8") | |
if proc.returncode != 0: | |
sys.exit(1) | |
logins = proc.stdout.split("\n") | |
for line in logins: | |
if not line.startswith(username): | |
# ignore lines that don't start with the username | |
continue | |
else: | |
matches = re.match(LOGIN_REGEXP, line) | |
if matches == None: | |
continue | |
else: | |
# got a match | |
login_end_time = matches.groups()[4] | |
if login_end_time == "still logged in": | |
return -1 | |
else: | |
last_time = time.mktime(time.strptime(login_end_time, "%Y-%m-%dT%H:%M:%S%z")) | |
return last_time | |
def get_uptime(): | |
"""Get system uptime.""" | |
with open('/proc/uptime', 'r') as f: | |
uptime_seconds = float(f.readline().split()[0]) | |
return uptime_seconds | |
def main(): | |
uptime_sec = get_uptime() | |
if uptime_sec < MIN_UPTIME: | |
# do not do anything if we have not hit minimum uptime | |
sys.exit(0) | |
last_login_time = get_last_login() | |
if last_login_time == -1: | |
# someone is still logged in, do nothing | |
sys.exit(0) | |
now = time.time() | |
if (now - last_login_time) > TIME_DELTA: | |
# trigger shutdown, since we are past the time delta | |
subprocess.Popen(["sudo", "shutdown", "-h", "now"]) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment