How can I tell if the lock screen is active from the command line on OS X?

3

1

I have a cron script that I want to run regularly if I am logged into my Mac. I don't want it to run if the Lock Screen is up. Is there a way to check from the command line / Terminal if the Lock Screen is activated?

cwd

Posted 2012-10-31T19:58:07.173

Reputation: 13 508

Answers

4

This is the exact implementation I also wanted. After a BUNCH of research, I put this applescript together with contributions from abarnert at https://stackoverflow.com/questions/11505255/osx-check-if-the-screen-is-locked

set queryUserLoginState to "python -c 'import sys,Quartz; d=Quartz.CGSessionCopyCurrentDictionary(); print d'"

tell the application "SleepDisplay" to launch
set displayOff to true
delay 2
repeat while displayOff
    set loginTest to do shell script queryUserLoginState
    if loginTest does not contain "CGSSessionScreenIsLocked = 1" then
        set displayOff to false
    end if
    delay 3
end repeat

-- do stuff!

Now, I know you asked for a terminal check to see if the screen is locked; it's implemented in the code.

I'll point in out here:

If the result of the terminal command:

python -c 'import sys,Quartz; d=Quartz.CGSessionCopyCurrentDictionary(); print d'

contains the entry

CGSSessionScreenIsLocked = 1

Then the screen is currently locked. When it does not contain that line, the user is logged in (that is to say, the password has been entered at the lock screen).

programmeric

Posted 2012-10-31T19:58:07.173

Reputation: 56

Oh, I also needed to check for the variable CGSSessionOnConsoleKey as was posted in your link :) – cwd – 2012-11-01T16:35:30.527

The only problem seems to be if this is run from a cron script then the python bit returns None instead of outputting the data. Any tips? – cwd – 2012-11-05T20:58:14.897