Last active
March 13, 2021 15:39
-
-
Save codeskipper/3a57a5809b561599663fbb584537bd2a to your computer and use it in GitHub Desktop.
macOS - python - Detect active user at console (must run locally)
This file contains 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 | |
# Check for user presence at console by checking for screen lock and console login status | |
# Thanks to https://stackoverflow.com/users/908494/abarnert at | |
# https://stackoverflow.com/a/11511419/4326287 | |
import sys | |
import Quartz | |
from datetime import datetime | |
from dateutil.tz import tzlocal | |
import time | |
while True: | |
try: | |
# python2 way | |
timestamp=datetime.now(tzlocal()).replace(microsecond=0).isoformat(' ') | |
d=Quartz.CGSessionCopyCurrentDictionary() | |
userPresent=(d and | |
d.get("CGSSessionScreenIsLocked", 0) == 0 and | |
d.get("kCGSSessionOnConsoleKey", 0) == 1) | |
if userPresent: | |
print(timestamp + ' [userPresence.py] User presence detected') | |
else: | |
print(timestamp + ' [userPresence.py] Screen is locked or user is not logged in at console') | |
time.sleep(10) | |
# break | |
except KeyboardInterrupt as error: | |
print(timestamp + ' [userPresence.py] Received interrupt (^C) - terminating\n') | |
break | |
sys.exit(userPresent) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment