Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

I want to write an init service script which runs the program as a particular user (and not root). I will then chkconfig this script and install into my production run level.

I could just put a su command in the script but I was wondering if there is a best practise of doing this.

Thanks, Garry

share|improve this question

3 Answers 3

up vote 7 down vote accepted

You can just su. You won't need the password because the script will initally be running as root.

There's also the runuser command.

If you use /etc/init.d/functions you can use the daemon function which has an option for specifying the user to run as.

I'd personally sway towards the latter all other things being equal.

share|improve this answer
1  
This a the prefered solution: stay as close as possible to the way the OS provided initscripts work. Use /etc/init.d/functions. It'll even provide you with green OK and red FAIL messages when starting the initscript. –  wzzrd Jun 19 '09 at 14:54

If you write a redhat-style init script, the daemon function has a --user option.

daemon --user=$runasuser --pidfile="$PIDFILE" $yourbinary $youroptions
share|improve this answer

The best practice might be to use sudo, and modify the necessary files to make sure it happens automatically without being prompted for a password. If you don't mind the password being in the script, I think you can do something like

 echo password | sudo -S -u username command

What are you doing? Maybe there's a better way?

EDIT

Thanks TCampbell

share|improve this answer
1  
If using sudo, you'd want to add the -u <run as user> and consider using the NOPASSWD option for that user/command combination. –  TCampbell Jun 19 '09 at 14:09
    
Edited. Thanks for reminding me! –  Matt Simmons Jun 19 '09 at 14:23
    
Well it's currently been run as root so su doesn't require any password (editing of /etc/sudoers will allow sudo to run with a password as well). But is this the preferred method? We have some in-house developed software which I want to write service scripts for. I don't want this software to be run as root though (for obvious reasons). –  Garry Harthill Jun 19 '09 at 14:40
3  
I strongly advise against using sudo in init scripts. sudo is meant for users to do stuff without knowing the root password. Since an init script is run as root anyway, there is no need to use sudo. Sudo will only needlessly complicate things. –  wzzrd Jun 19 '09 at 14:53
    
Using sudo in an init script will fail if requiretty is enabled in /etc/sudoers (on by default in cent 6 and cent 7)github.com/influxdb/influxdb/issues/800 –  spuder Oct 10 at 16:41

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.