Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Lock and unlock OSX from http request.
var applescript = require('applescript');
var http = require('http');
var script =
'tell application "System Events"\n\
if name of every process contains "ScreenSaverEngine" then \n\
tell application "ScreenSaverEngine"\n\
end tell\n\
delay 0.2\n\
else \n\
tell application "Terminal"\n\
do shell script "caffeinate -u -t 1"\n\
end tell\n\
delay 0.5\n\
end if\n\
keystroke "YOUR_PASSWORD"\n\
keystroke return\n\
get computer name of (system info)\n\
end tell';
function onRequest(req, res) {
if (req.url == '/unlock') {
if (!exec('python -c \'import sys,Quartz; d=Quartz.CGSessionCopyCurrentDictionary(); sys.exit(d and d.get("CGSSessionScreenIsLocked", 0) == 0 and d.get("kCGSSessionOnConsoleKey", 0) == 1)\'')['code']){
applescript.execString(script, function(err, rtn) {
if (err) console.error(err);
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write( err ? 'something went wrong while unlocking' : 'unlocked ' + rtn );
} else {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write('OSX isn\'t currently locked.');
} else if (req.url == '/lock') {
applescript.execString('do shell script "open /System/Library/Frameworks/ScreenSaver.framework/Versions/A/Resources/"');
} else {
res.writeHead(200, { 'Content-Type': 'text/plain' });

This comment has been minimized.

Copy link
Owner Author

OmgImAlexis commented Mar 8, 2015

To use this run the following line in terminal.
You must have node.js or a fork like io.js installed.

curl -o app.js && npm install -g nodemon && npm install shelljs && npm install applescript && clear && echo 'Install done'

Make sure to replace YOUR_PASSWORD in app.js with your own password and then run forever start app.js, to stop the process use forever stop 0.


This comment has been minimized.

Copy link

suhajdab commented Mar 13, 2015

No reason to go to shell from applescript to activate screensaver.
'tell application "System Events"\n
start current screen saver\n
end tell'

And thanks for the solution around lock screen detection! 😄

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.