Velvet Star Monitor

Standout celebrity highlights with iconic style.

updates

Run part of a bash script as a different user

Writer Andrew Mclaughlin

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

1

6 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?

4

# I=like:

#test if running bash as a different user works
sudo -u nobody bash -c : && RUNAS="sudo -u nobody"
echo 1: $USER
#Runs bash with commands between '_' as nobody if possible
$RUNAS bash<<_
echo 2: \$USER
_
echo 3: $USER

# ./run

1: root
2: nobody
3: root
2

This 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

3

This way, end of a script will be executed by different user (root). Please note the $[LINENO+2] and exit $? calls. These are required to make the end of the script to execute just once and to preserve the exit code of the sudo call.

#!/bin/bash
echo $USER
# pipe the rest of this script via a sudo call
tail -n +$[LINENO+2] $0 | exec sudo bash
exit $?
echo $USER
exit 1

For sonarqube:

sudo -u sonar /usr/bin/sonar start

where sonar is the name of user used to run the command /usr/bin/sonar start

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

3

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy