Running a Command as a Different User: Alternative Approaches

The primary purpose of “switching users” is to switch between different users, while the purpose of “executing commands as other users” is to run commands on behalf of another user. For instance, consider the following scenario:
Question: I have two users, userA and userB. userB needs to execute certain commands as userA. To configure this, I have made the following settings in the system:
When I ran the command as userB, it prompted me for userB’s password. After entering the password, the command did not provide the expected fdisk output.


Question:

I was contemplating the method of executing a command as a different user within a script.
“””.

The
script’s owner
is set as root. Additionally, the script includes the command to run as the hudson user:
“””.

su -c command hudson

Is this the correct syntax?



Solution 1:

Certainly, presenting the requested information, here is the

--help

:

$ su --help
Usage: su [options] [LOGIN]
Options:
  -c, --command COMMAND         pass COMMAND to the invoked shell
  -h, --help                    display this help message and exit
  -, -l, --login                make the shell a login shell
  -m, -p,
  --preserve-environment        do not reset environment variables, and
                                keep the same shell
  -s, --shell SHELL             use SHELL instead of the default in passwd

I conducted some testing by utilizing

sudo

since the password for the

nobody

account is unknown to me.

$ sudo su -c whoami nobody
[sudo] password for oli: 
nobody

When providing arguments to your command, it is necessary to enclose them in quotation marks. Failure to do so can result in unexpected outcomes. In this example, I am attempting to create a directory in /home/oli (as oli) while omitting the use of quotation marks for the entire command.

# su -c mkdir /home/oli/java oli
No passwd entry for user '/home/oli/java'

The value for the flag,

mkdir

, is only read and it attempts to use

/home/oli/java

as the username. By quoting it, the issue is resolved and it functions properly.

# su -c "mkdir /home/oli/java" oli
# stat /home/oli/java
  File: ‘/home/oli/java’
  Size: 4096        Blocks: 8          IO Block: 4096   directory
Device: 811h/2065d  Inode: 5817025     Links: 2
Access: (0775/drwxrwxr-x)  Uid: ( 1000/     oli)   Gid: ( 1000/     oli)
Access: 2016-02-16 10:49:15.467375905 +0000
Modify: 2016-02-16 10:49:15.467375905 +0000
Change: 2016-02-16 10:49:15.467375905 +0000
 Birth: -


Solution 2:


Please note that setting the script’s owner as root does not have any effect. Even if the setuid bit is set, it still does not work.


If you are running the script as root, you can use

sudo

. While

su

is mainly for
switching users
,

sudo

is intended for
executing commands
as other users. To execute the command as a specific user, utilize the

-u

flag.

sudo -u hudson command

Frequently Asked Questions