Cannot use 'defaults write' in self service policy

cddwyer
Contributor

I have created a policy that runs this script:

!/bin/bash

Get currently logged in user

currusr=ls -la /dev/console | cut -d " " -f 4
touch /var/log/screeen.log

Sotre cocoa dialog directory

CD='/Applications/Utilities/CocoaDialog.app/Contents/MacOS/CocoaDialog'

Create screenshot directory if it doesn't already exist

mkdir -m 777 -p /Users/$currusr/Pictures/Screenshots

chown -R $currusr:admin /Users/$currusr/Pictures/Screenshots

Move any screenshots from desktop to new folder

mv /Users/$currusr/Desktop/Screen Sho* /Users/$currusr/Pictures/Screenshots

Set screenshot folder as new location for screenshots as they're taken

su $currusr /usr/bin/defaults write com.apple.screencapture location /Users/$currusr/Pictures/Screenshots > /var/log/screeen.log 2>&1

su $currusr /usr/bin/killall SystemUIServer > /var/log/screeen.log 2>&1

Inform user

$CD msgbox --no-newline --text "Your screenshots have now been moved to Pictures > Screenshots." --button1 "OK"

exit 0

It is the defaults write command that fails. If I don't qualify the path to defaults the policy fails with 'could not execute binary' (whether I run it as user or root) when I do fully qualify the path to defaults it runs with no error but does not actually make the change, however, if run in terminal locally, the screencapture location changes successfully, please help this is driving me mad!

Thanks,
Christian

1 REPLY 1

thoule
Valued Contributor II

If you search these forums for "Run script as user" or something like that, you'll get lots of hits. Basically, Apple has been making it very difficult to run a program as a user. su $currusr just doesn't work these days. There was a bsexec line I used for a while, but it's always a headache.

Two solutions: first, search the forum for different ways to run as a user. Note that depending on your script, other parts may fail if they require root to run.

The second solution is to create a simple launchAgent and script and drop those in place on the system. A basic launchAgent can call a script when a user logs in to set the defaults command that that is run as the user without you fussing to make it happen.