Linux, su and sudo

I am running RHEL 6.5

I want to use a single command that will switch user, and then start a program that is only available within that user's environment.

Normally I would use two commands

su - mqm

runmqsc AAA <

Open in new window

I want to use a single su or sudo command to both switch to mqm, and then start up a program.

How would I write such a command ?

Los Angeles1Asked:
Who is Participating?
woolmilkporcConnect With a Mentor Commented:
If you don't want to get asked for a password you must be root to use "su -" like this:

su - mqm -c "/path/to/runmqsc AAA < /path/to/"

The "-" flag preserves the environment.

As an authorized sudo user you can do:

sudo -u mqm  "/path/to/runmqsc AAA < /path/to/"

This requires an entry in sudoers for the user "userA" issuing the command like

userA   ALL=(mqm) NOPASSWD:/path/to/runmsgc

There are three possible methods to preserve the target user's environment:

First method: The option "Defaults env_reset" must not be specified or (with the newer sudo implementations where it's the default) must be negated in sudoers:
Defaults !env_reset

Alternatively, some sudo implementations support the "-i" (=initialize environment)  flag, so you can try:

sudo -u mqm  -i "/path/to/runmqsc AAA < /path/to/"

A third alternative (if supported): Use the "SETENV" tag and "-E"

userA   ALL=(mqm) NOPASSWD:SETENV:/path/to/runmsgc

sudo -u mqm -E "/path/to/runmqsc AAA < /path/to/"
Try -
user /bin/su - mqm

Open in new window

You can substitute user with %groupname if you want to include a group.
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.