Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@kk7ds
Last active August 29, 2015 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kk7ds/5f28ce8ba0bc60c8908a to your computer and use it in GitHub Desktop.
Save kk7ds/5f28ce8ba0bc60c8908a to your computer and use it in GitHub Desktop.
Script to sleep machine based on login idle times
#!/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