0
root@Test:~# lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 20.04.5 LTS
Release:        20.04
Codename:       focal
root@Test:~#

I'm user1 and need to run a script as user2 and there must NOT be any password prompt. Added below line to sudoers (using visudo of course)

user1 ALL=(user2) NOPASSWD: /usr/local/bin/script.sh

and then I ran the below command as user1

sudo -u user2 /usr/local/bin/script.sh

it runs but a part of actual execution fails becoz of user2 's environment is NOT set.

Then I tried below -

sudo -i -u user2 /usr/local/bin/script.sh

But it asks for the password, if I type in the password then the script runs just fine. The problem is that it prompts for password which is a problem for automation. So my query is how could I run sudo -i without password prompt.

My setup:

root@Test:~# egrep "^[^#]|^#include" /etc/sudoers
Defaults env_reset
Defaults mail_badpass
Defaults secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin"
root ALL=(ALL:ALL) ALL
%admin ALL=(ALL) ALL
%sudo ALL=(ALL) NOPASSWD: ALL
user1 ALL=(user2) NOPASSWD: /usr/local/bin/script.sh
#includedir /etc/sudoers.d
root@Test:~#
root@Test:~# ls /etc/sudoers.d
README
root@Test:~#

Looks like setting the target user's ENV variables in the script itself is the only option but updating script is my last option, hence looking for a better/alt solution.

Appreciate any help, thanks!!

1 Answer 1

1

See what -i does [emphasis mine]:

-i, --login
Run the shell specified by the target user's password database entry as a login shell. This means that login-specific resource files such as .profile, .bash_profile, or .login will be read by the shell. If a command is specified, it is passed to the shell as a simple command using the -c option. The command and any arguments are concatenated, separated by spaces, after escaping each character (including white space) with a backslash (\) except for alphanumerics, underscores, hyphens, and dollar signs. If no command is specified, an interactive shell is executed. […]

(source)

You tried to do:

sudo -i -u user2 /usr/local/bin/script.sh

Assuming the target user's shell is bash, the command that your sudo run was like:

/bin/bash -c /usr/local/bin/script.sh

This is the command you want to allow with NOPASSWD in sudoers file. Note there is no -l that would force a login shell. sudo sets $0 to -bash and the leading dash is what makes this bash a login shell. Therefore you must not include -l in sudoers.

user1 ALL=(user2) NOPASSWD: /bin/bash -c /usr/local/bin/script.sh

If the target user's login shell is not /bin/bash then adjust the above line accordingly.

1
  • Thank you, worked great :) Can't upvote as I need 15 rep sorry but marked it as Solution.
    – Bateman
    Jan 16, 2023 at 23:26

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .