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.


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

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


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

sudo /usr/bin/osascript -e 'tell application "System Events" to do shell script "/System/Library/CoreServices/Menu\\ Extras/ -suspend"'

Make it executable using chmod +x command.

Step 5: Now specify this script path in['sh', '/Users/viny/Downloads/Python/'])

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/

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).


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