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:
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
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 containsuser.sh
root [other_user@my_server]$
if I then type
exit
I'm returned to my root account and the script completes execution-
#!/bin/bash bash /user.sh su - other_user -c /path/user.sh
output:
root -bash: /path/user.sh: Permission denied
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 toother_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