3

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

Garry Harthill
  • 864
  • 1
  • 11
  • 17

3 Answers3

9

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.

Jason Tan
  • 2,742
  • 2
  • 17
  • 24
  • 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
3

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

daemon --user=$runasuser --pidfile="$PIDFILE" $yourbinary $youroptions
Dan Pritts
  • 3,181
  • 25
  • 27
0

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

Matt Simmons
  • 20,218
  • 10
  • 67
  • 114
  • 1
    If using sudo, you'd want to add the -u and consider using the NOPASSWD option for that user/command combination. – TCampbell Jun 19 '09 at 14:09
  • 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)https://github.com/influxdb/influxdb/issues/800 – spuder Oct 10 '14 at 16:41
  • You think echo-ing the password is **best practice**? – Felipe Alvarez Apr 15 '16 at 00:00