4

I have a need to have a single script run the majority of its commands as another user, but do not want to instruct my users to call it via sudo. Running the commands with an EOF here document is not workable, as there are a lot of variables to pass from the input into various functions the script defines. Is there another way for me to run the functions as another user, while preserving the input and variables? Can this be done without calling a bunch of external files or adding sudo to nearly 300 commands?

2 Answers 2

3

You can use the su command as follows to do this in bash script:

su -c "command" -s /bin/sh Username

Where the -c parameter specifies spend a single command to the shell and -s is used to specify which shell to call the command.

Another way to do this is through the use of sudo as follows:

sudo -H -u Username bash -c "command" 

The -h parameter is a security policy that allows you to set the environment variable HOME to the specified user (root is by default). -u specifies the user to run the command.

1
  • In my case, this would not work, as there are a lot of input variables to pass and functions to call. One of my requirements is that the script be self-contained and be able to change its user while still handling the user-given input and calling the functions it defines. The script was already pretty fleshed out when the user requirement changed, and I wanted a way to accomplish this without re-writing it to call sudo almost every line.
    – MrDrMcCoy
    May 29, 2014 at 3:20
2

Putting this before the main functions are called did the trick for me:

    if [ "`whoami`" != "runasuser" ]; then
        sudo -u runasuser bash "$0" "$@"
        exit
    fi

This will call the current script in a sub shell as the user of your choice and pass all your input into it.

0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .