Run Self Service actions as the logged in user - not as root

AVmcclint
Honored Contributor

I'd like to put some simple items in Self Service that will help users do things on their own that don't require root access. For example, I'd like to make an item that does nothing but this:

rm -Rf ~/Library/Caches/*

But I can't figure out how to make it apply "~" to the logged in user instead of the root user. I've only created a policy that has the command inserted into the "Files and Processes" section. Is there a better way that doesn't require lots of scripting? I have other things that absolutely need to be run as the logged in user at login too but I can't get them to work because they only run as root from JSS.

7 REPLIES 7

sswartz
New Contributor III

Does the Flush User Caches option under the Maintenance section of a policy work for what you want?

stevewood
Honored Contributor II
Honored Contributor II

@AVmcclint have you tried the $3 variable:

rm -Rf /Users/$3/Library/Caches/*

Or, the way to make sure you have the right user:

loggedInUser=`/bin/ls -l /dev/console | /usr/bin/awk '{ print $3 }'`
rm -Rf /Users/$loggedInUser/Library/Caches/*

Of course the easiest thing is to do what @sswarts recommends and use "Flush User Caches" under Maintenance.

davidacland
Honored Contributor II
Honored Contributor II

In one of our scripts we're using /Users/$USER. I thought that would still bring back root but it seems to be working!

AVmcclint
Honored Contributor

I forgot about the Flush User Caches under Maintenance. I'll use that. I tried using $3 but it didn't work. /Users/$USER appears to have worked for this particular test only because it is specifying a path. I'm not sure if it will work with other things that have to actually be run as the current user. There is still a need to allow users to run various tasks as themselves.

mm2270
Legendary Contributor III

For running commands as the user and not as root, you could try something like:

username=$(ls -l /dev/console | awk '{print $3}'); sudo -u $username <commands to run go here>

I've used similar syntax in some of my Self Service scripted policies and it has always worked from what I recall. The above could be used in the Run Command field instead of a full blown script, as long as the command(s) to run are fairly simple.

davidacland
Honored Contributor II
Honored Contributor II

@AVmcclint, I've tried that before but $3 only seems to work at login.

elliotjordan
Contributor III

We use stat to determine the logged in user. It seems to work reliably, even with Fast User Switching enabled.

#!/bin/bash
CURRENT_USER=$(/usr/bin/stat -f%Su /dev/console)
rm -Rf "/Users/$CURRENT_USER/Library/Caches"/*