Monday, December 4, 2023
rated 0 times [  527] [ 0]  / answers: 1 / hits: 940113  / 1 Year ago, thu, august 25, 2022, 3:36:03

I would like to run a script from the main ubuntu shell as a different user that has no password.

I have full sudo privileges, so I tried this:

sudo su -c "Your command right here" -s /bin/sh otheruser

Then I have to enter my password, but I am not sure if that script is now really running under that user.

How can I confirm that the script is really running under that user now?

More From » command-line


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

(Starting from Ubuntu 19.10, -H is no longer needed as this is now the default behaviour. See: How does sudo handle $HOME differently since 19.10?)

-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
auth [success=ignore default=1] user = otheruser
auth sufficient use_uid user ingroup somegroup

Then test from terminal

rubo77@local$ su otheruser -c 'echo "hello from $USER"'
hello from otheruser

[#31225] Friday, August 26, 2022, 1 Year  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.

Total Points: 361
Total Questions: 103
Total Answers: 113

Location: Turkmenistan
Member since Sun, Aug 2, 2020
3 Years ago
fenddy questions
Tue, Nov 22, 22, 10:11, 1 Year ago
Tue, Sep 27, 22, 09:16, 1 Year ago
Wed, Dec 28, 22, 13:09, 1 Year ago
Fri, Jun 18, 21, 14:04, 3 Years ago