Execute script as another user

I need to create one script that will require me to execute separate scripts as other users.

For example:
execute script 1 as user1
execute script 2 as user2
execute script 3 as user3

This script starts services that need to be ran as a particular user.

How do you execute a script as a different user within a script? I imagine Ill have to add credentials or setup RSA?
Using RHEL.
Who is Participating?
Shiju JacobInfo SecurityCommented:
You can add this command into you script

bin/su - oracle -c "/path/to/backup_db.sh /tmp/test"

Breaking it down:
 /bin/su : switch user
 - : option to su, make it a login session (source profile for the user)
 oracle: user to become
 -c "/path/to..." : command to run
"su - user" only works without a password if you are root.

if you aren't running the first script as root, you could, as you suggest, set up ssh keys between various users.

Create ssh keys for the user running the main script.  The add that user's .ssh/id_rsa.pub file to the .ssh/authorized_keys file of the other users (user1, user2 and user3 in your example).

The to run a script as user1 you could
    ssh user1@localhost /path/to/command parm1 parameter2 p3

(note that you don't need quotes round the "remote" command for ssh).

Remember that the environment for the /path/to/command will not be the same as the envronment in the main script - you may need to pass variables on the command line, or in an environment file.
Another approach is to use sudo, eg:

sudo -u user1 /path/to/script1
sudo -u user2 /path/to/script2
sudo -u user3 /path/to/script3

where the sudoers entries would look like:

user  (user1) NOPASSWD: /path/to/script1
user (user2) NOPASSWD: /path/to/script2
user (user3) NOPASSWD: /path/to/script3
k3vsmithAuthor Commented:
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.