Lock Screen using terminal? Osascript is preventing keystrokes

applescriptscreen-lockterminal

I want to lock my Mac's screen remotely. I don't want to sleep my Mac. Only the screen. I don't want to require a password every time I put my monitor to sleep (system prefs/require password). And I definitely don't want to suspend the current user (CGSession -suspend) because my Mac also serves as a media control center.

I tried using an applescript to create an app I could launch remotely, but this command in the applescript fails:

 tell application "System Events"
      key code 12 using {command down, control down}
 end tell

When I launch the applescript over terminal, I get an error telling me that osascript is not allowed to send keystrokes.

Here's what I'm trying to accomplish: I have a Philips Hue dimmer remote near my home's front door. I've reprogrammed the buttons to do various things (lights on, restart playing whatever I was listening to on iTunes last, etc). It's great, except, I want the OFF button to turn off my lights, stop iTunes, etc, and lock my Mac's monitor. Everything works but that last step.

I can sleep my Mac's monitor using

do shell script "pmset displaysleepnow"

I've settled with that for now, but that sleeps the monitor. I want to lock the monitor.

I know I could go into system prefs and require a password after sleep, but I don't want to use a password every time I sleep my monitor. That would drive me crazy. I also know I could do something like this:

do shell script "/System/Library/CoreServices/Menu\\ Extras/User.menu/Contents/Resources/CGSession -suspend"

But that suspends the current user's session, which prevents my remote from controlling my Mac. I just want to lock my monitor (command control Q) without using a hotkey, so I'll be able to trigger it remotely.

How can I lock my Mac's screen remotely?

Best Answer

I found an answer.

The Lock Screen app on Github does exactly what I wanted to do. So, by downloading it and adding this to my script, I can lock my monitor remotely:

run application "Lock Screen"

Edit: It seems the application runs the following script:

activate application "SystemUIServer"
tell application "System Events"
    tell process "SystemUIServer" to keystroke "q" using {command down, control down}
end tell

Adding that to my applescript still gives me an osascript error, but triggering the Lock Screen app using applescript works perfectly for my needs.

This makes me happy!

I have a remote at my door that I programmed to turn my lights on when I click the ON button, and when I click OFF, it turns my lights off, makes sure various smart devices are off, and it locks my Mac's monitor.

If I'm headed out the door, OFF makes sure everything is off and the Mac's monitor is locked.

Love it!