Skip to content

Instantly share code, notes, and snippets.

@zerok
Created January 15, 2018 20:46
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 zerok/96ff78adbbf2105dd116b20aadc07718 to your computer and use it in GitHub Desktop.
Save zerok/96ff78adbbf2105dd116b20aadc07718 to your computer and use it in GitHub Desktop.
YubiKey locking if unplugged
#!/usr/bin/env python3
import time
import subprocess
from datetime import datetime
from datetime import timedelta
def lock():
subprocess.check_call("""osascript -e 'tell application "System Events" to start current screen saver'""", shell=True, stderr=subprocess.STDOUT)
def check():
try:
subprocess.check_call('ioreg -p IOUSB | grep Yubikey > /dev/null', shell=True)
return True
except:
return False
def main():
locked_before = None
plugged_in_before = None
threshold = timedelta(seconds=60)
while True:
now = datetime.now()
plugged_in_now = check()
if plugged_in_before is None:
plugged_in_before = plugged_in_now
if plugged_in_before and not plugged_in_now:
if locked_before is None or now - locked_before > threshold:
lock()
locked_before = now
if now - locked_before >= threshold:
plugged_in_before = plugged_in_now
time.sleep(2)
if __name__ == '__main__':
main()
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC -//Apple Computer//DTD PLIST 1.0//EN http://www.apple.com/DTDs/PropertyList-1.0.dtd >
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.zerokspot.yubikey-autolock</string>
<key>ProgramArguments</key>
<array>
<string>/usr/local/bin/python3</string>
<string>/Users/zerok/.local/bin/autolock.py</string>
</array>
<key>KeepAlive</key>
<true />
</dict>
</plist>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment