slock-usb-key (863 bytes)
1 #!/usr/bin/env python3 2 # Lock the screen with slock when a USB key is unplugged; unlock when replugged. 3 # Usage: put the key's ID_SERIAL in ~/.slock-usb-key; allow NOPASSWD sudo killall. 4 5 6 from os.path import expanduser 7 from subprocess import Popen 8 9 import signal 10 import pyudev 11 12 13 signal.signal(signal.SIGCHLD, signal.SIG_IGN) 14 15 try: 16 with open(expanduser('~/.slock-usb-key'), 'r') as fp: 17 serial = fp.read().strip() 18 except OSError as e: 19 raise SystemExit(f'slock-usb-key: {e}: put the key ID_SERIAL there') 20 21 context = pyudev.Context() 22 monitor = pyudev.Monitor.from_netlink(context) 23 monitor.filter_by('block', 'disk') 24 for device in iter(monitor.poll, None): 25 if device.get('ID_SERIAL') == serial: 26 if device.action == 'add': 27 Popen(['sudo', 'killall', 'slock']) 28 elif device.action == 'remove': 29 Popen(['slock'])