Auto-Lock Your Unattended Mac using Python

How often have you received a mail from a colleague with subject line“Pizza on my seat, please help yourself” and in the end it turned out that it was a prank mail sent by someone else who found the system unattended/unlocked and decided to have some fun :)?

In this post we’ll have some fun with Python to auto-lock our system whenever we are not around, and save ourself from pranksters.

Note: Code given here works for Mac. However you can easily modify the code to make it work on Windows also.

Step 1: Allow your user to execute sudo commands without password. You can use visudo command to make an entry similar to this.

viny ALL=(ALL) NOPASSWD: ALL

Step 2: Install required python packages using following commands:

pip3 install cmake
pip3 install face_recognition
pip3 install opencv-python

Step 3: Download code given at https://raw.githubusercontent.com/vinycoolguy2015/awslambda/master/lock_system.py

You’ll need to provide one image of yours. Change this line in the code with the path where your image is stored.

known_image=face_recognition.load_image_file("/Users/viny/Downloads/Python/vinayak.jpg")

Step 4: Now create a shell script named lock_system.sh with following code

#!/bin/bash
sudo /usr/bin/osascript -e 'tell application "System Events" to do shell script "/System/Library/CoreServices/Menu\\ Extras/User.menu/Contents/Resources/CGSession -suspend"'

Make it executable using chmod +x lock_system.sh command.

Step 5: Now specify this script path in lock_system.py.

subprocess.call(['sh', '/Users/viny/Downloads/Python/lock_system.sh'])

Step 6: Now our code is ready and all we need to do is to schedule a cron, similar to this.

* * * * * /usr/local/bin/python3 /Users/viny/Downloads/Python/lock_system.py

That’s all. Now our setup is ready. Try moving away from the system and once the code is executed, system will be locked. You can also test it by specifying a different image(which is not yours obviously).

known_image=face_recognition.load_image_file("/Users/viny/Downloads/Python/unknown.jpg")

That’s all folks. Stay safe from pranksters :)