Search code examples
linuxbashrootsudorhel

As a root user can I execute commands in BASH as another user without requiring a password?


I have a root user account on an RHeL server. On that server I have a simple script called user.sh that just returns the current user:

#!/bin/bash
echo $USER

when run from my root account the output is

bash user.sh
>>>root

From another script I would like to be able to temporarily switch between users without entering a password, storing the password in the script or a file, or modifying /etc/sudoers and execute user.sh and then return back to my initial root account. Is this at all possible?

Here's what I've tried so far:

  1. Using delimeters to execute a block of code

    #!/bin/bash
    
    bash /user.sh
    
    su other_user <<EOF
    echo Current user: $USER
    EOF
    

    output:

    root
    Current user: root
    
  2. switching to a user in bash, executing a command and then logging back out

    #!/bin/bash
    
    bash /user.sh
    
    su other_user
    bash /user.sh
    exit
    

    output: The script pauses execution and returns me to the terminal logged in as other_user however I will still be in my root account's directory that contains user.sh

    root
    [other_user@my_server]$
    

    if I then type exit I'm returned to my root account and the script completes execution

  3. using the su - <username> -c /path/to/the/shellscript.sh to execute a script as a different account and then return

    #!/bin/bash
    
    bash /user.sh
    
    su - other_user -c /path/user.sh
    

    output:

    root
    -bash: /path/user.sh: Permission denied
    
  4. using sudo -i -u other_user to log in as the user and execute the script which yields the same problem experienced with attempt #2 but I am redirected to other_user's home directory.

It may be worth noting that if I use method 2, while I'm logged in as other_user I am able to run bash user.sh and yield the desired output: other_user


Solution

  • In the second example, the $USER variable is expanded before su is executed. This can be prevented by quoting EOF.

    su other_user <<'EOF'
    echo Current user: $USER
    EOF
    

    Or you can execute the script to do it in the root shell, also using a here-doc:

    su other_user <<END
    bash user.sh
    END
    

    or you can use the -c option to su:

    su other_user -c 'bash user.sh'