After looking at all the suggestions here, I've discovered a few things which I hope will be useful to others in my position:
hop is right to point me back
at /etc/init.d/functions
: the
daemon
function already allows you
to set an alternate user:
daemon --user=my_user my_cmd &>/dev/null &
This is implemented by wrapping the
process invocation with runuser
-
more on this later.
Jonathan Leffler is right: there is setuid in Python:
import os
os.setuid(501) # UID of my_user is 501
I still don't think you can setuid from inside a JVM, however.
Neither su
nor runuser
gracefully handle the case where you
ask to run a command as the user you
already are. E.g.:
[my_user@my_host]$ id
uid=500(my_user) gid=500(my_user) groups=500(my_user)
[my_user@my_host]$ su my_user -c "id"
Password: # don't want to be prompted!
uid=500(my_user) gid=500(my_user) groups=500(my_user)
To workaround that behaviour of su
and runuser
, I've changed my init script to something like:
if [[ "$USER" == "my_user" ]]
then
daemon my_cmd &>/dev/null &
else
daemon --user=my_user my_cmd &>/dev/null &
fi
Thanks all for your help!