Run a shell script as another user that has no password
You can do that with su
or sudo
, no need for both.
sudo -H -u otheruser bash -c 'echo "I am $USER, with uid $UID"'
The relevant parts of man sudo
:
-H The -H (HOME) option requests that the security policy set
the HOME environment variable to the home directory of the
target user (root by default) as specified by the password
database. Depending on the policy, this may be the default
behavior.
-u user The -u (user) option causes sudo to run the specified
command as a user other than root. To specify a uid
instead of a user name, use #uid. When running commands as
a uid, many shells require that the '#' be escaped with a
backslash ('\'). Security policies may restrict uids to
those listed in the password database. The sudoers policy
allows uids that are not in the password database as long
as the targetpw option is not set. Other security policies
may not support this.
su
can only switch user without providing a password if you are root. See Caleb's answer
You can modify the /etc/pam.d/su
file to allow su
without password. See this answer.
If you modified your auth file to the following, any user that was part of group somegroup
could su
to otheruser
without a password.
auth sufficient pam_rootok.so
auth [success=ignore default=1] pam_succeed_if.so user = otheruser
auth sufficient pam_succeed_if.so use_uid user ingroup somegroup
Then test from terminal
rubo77@local$ su otheruser -c 'echo "hello from $USER"'
hello from otheruser
If you want to use su instead of sudo, I believe you can use something like this:
su - <username> -c "<commands>"
-
will simulate a login of the specified user-c
tells it that you want to run a command
ps. Unfortunately I'm not able to install ruby using rvm with this method, but that's probably not related.
The answers above are really useful to me but to answer the actual question...
How can I affirm that the script is really running under that user now?-
Use:
ps -ef | grep <command-name>
The output should include your script and the actual user executing it. People on BSD-like systems, e.g. MAC can find similar information with:
ps aux | grep <command-name>