Is there a way to unlock and lock screen from command line, via ssh? I know /System/Library/CoreServices/Menu\ Extras/User.menu/Contents/Resources/CGSession -suspend
command, but it doesn't seem to work via ssh. The perfect solution would be a command, that I could type logged via ssh and it would unlock the screen or lock it back again, so I don't need to tell anybody my password, if he wants to use it. Is there any builtin tool, that would provide such functionality?
-
Check this answer (I'm using this method, and it works flawlessly).– glcCommented Jan 21, 2017 at 17:10
3 Answers
There are many ways to lock and unlock your Mac via SSH. The easiest and probably the fastest way is to use osascript
(applescript).
Locking Mac
To do this, log in via ssh and type in
osascript -e 'tell application "Finder" to sleep'
You can switch Finder for System Events, but that means more characters to type.
Unlocking Mac
To wake your Mac is a little harder.
There are two ways to do this.
You can use osascript
again.
osascript -e 'tell application "System Events" to key code 123'
This tells it to keystroke the left arrow key which should wake your Mac up from sleep.
You can also use the pmset
command.
pmset schedule wake "mm/dd/yyyy 00:00:00"
Use a date and time that has already passed.
Of course you will need to keystroke your password via Applescript, e.g.
osascript -e 'tell application "System Events" to keystroke "password"'
An alternative to this could be the Remote Wake Up app for Mac, but I am not sure if you can put a password in.
-
I know, about the ability to make osx sleep remotely. I have been looking for something, that will just lock the screen, not put the computer to sleep. Something like win + L on windows, but via ssh. Also, I cant get to work this unlocking script.– fulaphexCommented Mar 14, 2016 at 17:04
-
@fulaphex
pmset displaysleepnow
seems to work for me: it will put the display to sleep immediately, and because in preferences/security&privacy/general I have "require password immediately after sleep or screen saver begins", it will also lock the station. Commented May 8, 2020 at 9:22 -
Shouldn‘t the Mac already be running/woken up to allow osascript to run?– nohillside ♦Commented Oct 10, 2022 at 17:42
-
I use this for locking the screen (works on Big Sur):
osascript -e 'tell application "System Events"
keystroke "q" using {control down, command down}
end tell'
I use this:
sudo -S pmset schedule wake "$(date -j -v +2S +'%m/%d/%y %H:%M:%S')"
Wakes your Mac up in 2 seconds from now. (Interestingly enough, 1 second doesn't work.)
Good luck (to way over in 2016 😜)!