It seems when sudo
ing down that using sudo -u $user
that the environment of root is still being used. How can I make sudo
use the users environment? as a special note not all users that I will be using this on have login shells.
3 Answers
Try sudo -i -u $user
gerald@book:~$ env |grep HOME
HOME=/home/gerald
gerald@book:~$ sudo -u ubuntu env |grep HOME
HOME=/home/gerald
gerald@book:~$ sudo -i -u ubuntu env |grep HOME
HOME=/home/ubuntu
-
unfortunately doesn't work if they don't have a shell in
/etc/passwd
:( but it'll do I guess... Dec 3, 2010 at 10:39 -
Looking at the man page, it seems that
-E
is the one that preserves the environment, i.e. all the environment variables etc are there, although it still doesn't setPATH
andLD_LIBRARY_PATH
to the calling user's.– ShahbazJun 17, 2013 at 15:22 -
1
-
Do you know if there is any way to prevent the command from being run from the user's home directory instead of the current directory?– pooya13Jun 9, 2021 at 5:51
man sudoers
on Debian mentions another possibility. Not sure which way around you want, but your question sounds like you would want to have the env_reset
option from /etc/sudoers
- the opposite is basically the env_keep
list. In order to set the proper HOME
you can use the -H
option to sudo
directly or, again in sudoers
, with the always_set_home
option.
Alternatively you could use env_file
to specify an exact environment you want to pass. However, I think it is best if you check out the env_*
options from man sudoers
, because /etc/sudoers
controls it all and that's the point to turn to.
Here's part of the context in which I use env_reset
inside my sudoers
file:
Defaults !lecture
Defaults env_reset
Defaults syslog=auth
Defaults log_year
When sudoing environment variables are not preserved.
In my case, I use here-document.
You put your actions such as my_script.sh
inside your HERE DOCUMENT :
su -u some_user <<EOF
./my_script.sh
EOF
You should not put variable directly here, as they would be interpreted from your current user.
su -u some_user <<EOF
./my_script.sh $MY_VAR
EOF
If $MY_VAR
is not set for the user running the script, it won't be set.
You variable must be called inside your scripts, or you must escape them with \
.
Eg.
su -u some_user <<EOF
./my_script.sh \$MY_VAR
EOF
Here, $MY_VAR
will have some_user
contextual value.
-
Good answer. One small correction: It should be
su - some_user
instead ofsu -u some_user
. Jun 25, 2019 at 6:30
# whoami => root # sudo -u user whoami => user
sudo -u user
is analogous tosu user
to switch the env in su you have to usesu - user
-u
also ignores groups... I tried something from root (using sudo -u down) and it worked, apparently it didn't for the user... so I have to make sure I'm running commands in a way that would have all there limitations and environmental issues.