Last active
August 29, 2015 14:14
-
-
Save kk7ds/5f28ce8ba0bc60c8908a to your computer and use it in GitHub Desktop.
Script to sleep machine based on login idle times
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/python | |
import datetime | |
import subprocess | |
import sys | |
import time | |
now = datetime.datetime.now() | |
if now.hour > 6 and now.hour < 19: | |
timeout_hours = 4 | |
else: | |
timeout_hours = 1 | |
TIMEOUT = 60 * 60 * timeout_hours | |
def get_idle(): | |
w = subprocess.check_output('w -sh | awk \'{print $3}\'', shell=True) | |
min_idle = 30 * 24 * 3600 | |
for line in w.split('\n'): | |
if 'm' in line: | |
hours, mins = line.split(':') | |
secs = 0 | |
mins = mins.replace('m', '') | |
idle = int(hours) * 3600 + int(mins) * 60 + int(secs) | |
elif ':' in line: | |
try: | |
mins, secs = line.split(':') | |
hours = 0 | |
except ValueError: | |
hours, mins, secs = line.split(':') | |
idle = int(hours) * 3600 + int(mins) * 60 + int(secs) | |
elif '.' in line: | |
secs, frac = line.split('.') | |
idle = int(secs) | |
else: | |
continue | |
if idle < min_idle: | |
min_idle = idle | |
return min_idle | |
def sleep(): | |
with file('/sys/power/state', 'w') as f: | |
f.write('mem') | |
subprocess.call('nmcli con down id em1', shell=True) | |
subprocess.call('nmcli con up id em1', shell=True) | |
idle = get_idle() | |
should_sleep = idle > TIMEOUT | |
try: | |
should_sleep = sys.argv[1] | |
except: | |
pass | |
if should_sleep: | |
sleep() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment