Is there a way to make part of a script run as a different (non-root) user? If it helps , the part to be run as a different user occurs at the end of the script

Edit :
OS -> Ubuntu 9.04

link|improve this question

67% accept rate
feedback

3 Answers

Use the sudo command in the script.

In the form:

sudo -u _username_ _command_

the sudo command runs command as the user username.

If the script is being run as root, I don't think it will prompt for a password. Otherwise, this article discusses how to use sudo with password in one command line?, and this article discusses how to use sudo without password?

link|improve this answer
feedback

EricJLN's answer is good, but the serverfault advice is slightly dangerous - would allow anyone to run anything as root! So I'm posting here because I can't format the comment.

I would recommend using visudo to give the permissions you need as precisely as you can. Type visudo and add a line like:

username hostname = NOPASSWD: /full/path/to/command1, full/path/to/command2

If you do need to run this same thing on many hosts, you could open it up with:

username ALL = NOPASSWD: /full/path/to/command1, full/path/to/command2

But I would *not use either:

username ALL=(ALL) NOPASSWD: ALL

or username hostname = ALL

The sudoer man page has lots of gory details

link|improve this answer
Would it work for a command available to a particular user only ? – Manish Mathai Jan 9 '10 at 9:42
You can specify that only particular users can run the command (in the examples above, replace username with the username who should be able to run the command). If the executable you want to run is only executable by one particular user, that's fine too - just pass that username in the sudo -u username commandline line of the script. – James Polley Jan 9 '10 at 10:31
@Manish. Yes. What the sudoers file says is "Allow this username on this host to run command1 without having to provide a password. – DaveParillo Jan 9 '10 at 17:23
feedback

not so sure about it, but if you want that ONLY the end of that script will run as a different user, you could add su someuser before the end of the script.

Am I missing something?

Hope that helps,

Regards

link|improve this answer
feedback

Your Answer

 
or
required, but never shown

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