Get users home directory when they run a script as root - bash

I have a sh script that needs to be run as root, however it is run by the end user using sudo. How can I get the users home directory when ~/ points to /root when running with sudo?

Try to avoid eval. Especially with root perms.
You can do:
USER_HOME=$(getent passwd $SUDO_USER | cut -d: -f6)
Update:
here is why to avoid eval.

The user's home directory would be ~$SUDO_USER. You can use eval as follows:
USER_HOME=$(eval echo ~${SUDO_USER})
echo ${USER_HOME}

$ sudo env |grep USER
USER=root
USERNAME=root
SUDO_USER=glglgl
So you can access $SUDO_USER and ask the system for his homedir with getent passwd $SUDO_USER | cut -d: -f6.

Try accessing the environment variable $SUDO_USER

Unless I misunderstood the question, when the user runs the script with sudo, the $HOME environment variable does not change. To test out, I created this script:
#!/bin/bash
#sudo_user.sh
env | grep -e USER -e HOME
... and run it:
sudo ./sudo_user.sh
Output:
USER=root
HOME=/home/haiv
USERNAME=root
SUDO_USER=haiv
The output tells me that $HOME is still pointing to the user's home (in this case, /home/haiv).

It comes to a little improvement for the eval solution.
Before sending the username variable to eval, test it with the user existence, so if there's arbitrary code, it won't pass the check.
#? Description:
#? Get the user's home directory by username regardless of whether is running with `sudo`.
#? The username is checked, it must exist, to avoid the arbitrary code execution of `eval`.
#? The returned home directory's existence is not checked.
#?
#? Usage:
#? #home USERNAME
function home () {
if id "$1" >/dev/null 2>&1; then
eval echo "~$1"
else
return 255
fi
}
Run the code on macOS:
$ home root
Output:
/var/root
If you run it with something like:
home 'root ; ls'
It gives nothing and returns an error, the ls won't be executed.

You can use Hai's incomplete answer to very simply construct the user's home directory. He and others correctly state that you can get the original user while in the sudo shell. You can use that to construct the home directory into a new variable called user_home (or whatever you like):
#user_home="/home/${$SUDO_USER}";

Related

Testing home directory of current user with sudo [duplicate]

If I create the script /root/bin/whoami.sh containing:
#!/bin/bash
whoami
and this script is called by a user with a properly configured sudo, it will indicate
root
Is there a fast way to obtain the actual user in a script, or will I have to resort to parameters passing along this username?
$SUDO_USER doesn't work if you are using sudo su -.
It also requires multiple checks - if $USER == 'root' then get $SUDO_USER.
Instead of the command whoami use who am i. This runs the who command filtered for the current session. It gives you more info than you need. So, do this to get just the user:
who am i | awk '{print $1}'
Alternatively (and simpler) you can use logname. It does the same thing as the above statement.
This gives you the username that logged in to the session.
These work regardless of sudo or sudo su [whatever]. It also works regardless of how many times su and sudo are called.
I think $SUDO_USER is valid.
#!/bin/bash
echo $SUDO_USER
whoami
Here is how to get the username of the person who called the script no matter if sudo or not:
if [ $SUDO_USER ]; then user=$SUDO_USER; else user=`whoami`; fi
or a shorter version
[ $SUDO_USER ] && user=$SUDO_USER || user=`whoami`
Using whoami, who am i, who, id or $SUDO_USER isn't right here.
Actually, who is never a solution to the question, as it will only list the logged in users, which might be dozens...
In my eyes, the only valuable answer is the use of logname.
Hope this helps
Rob
If it's the UID you're looking for (useful for docker shenanigans), then this works:
LOCAL_USER_ID=$(id -u $(logname))
who am i | awk '{print $1}' didn't work for me but
who|awk '{print $1}' will serve the job
Odd, the system does distinguish between real and effective UIDs, but I can find no program that exports this at shell level.

How to get the user of the parent process?

I'm writing a program which uses its own config files (in /etc/program/ and ~/.config/program/)
The problem is sometimes it needs to be executed as root (so most of the time with sudo) and in this case ~/.config/program is actually in root's directory (/root in my case)
I want my program to use the user's config file even if used with sudo. My idea is to first get the parent program's PID (in my case BASH) -- which is normally executed by a normal user -- and then get the name of the user executing the parent program. I easly found out how to get the PPID, but I didn't found how to find the name of the user.
I imagine a script like :
parents_name=$(echo $PPID | *command_which_gives_the_name_from_a_PID*)
. /home/$parents_name/.config/program # includes the user's config file
I hope someone have an awnser !
sudo adds the name of the invoking user to the environment of the command.
. /home/$SUDO_USER/.config/program
$HOME might already be the same as /home/$SUDO_USER, but there are too many ways to configure sudo to make it the home directory of the target user.
However, that makes your script dependent on being called by sudo. Better to be explicit and pass the path of the desired configuration to the script as an argument. Something like
sudo theScript "$HOME/.config/program"
and
. "$1"
To get the user of a process
$ ps u -p 2813
To strip it out
$ ps u -p 2813 | awk '{print $1}'
USER
john
Or
$ ps -o user= -p 2813
john
https://unix.stackexchange.com/questions/284934/return-owner-of-process-given-pid/284938 has a similar question. The accepted answer was to use ps -o user= -p PIDHERE. So, in your case, you'd do something like:
parents_name=$(ps -o user= -p $PPID)
In this case, we don't want column headers, so we add --no-headers.

Running some parts of the script with root and other parts with normal user

To make sure my bash script runs as root I use:
if [ "$UID" -ne "0" ]; then
echo "You must root to run $0. Try following"
echo "sudo $0"
exit 9
fi
But in the script, there some commands that I want to run with sudo -u $USER, however, if I run the whole script as root it comes out as sudo -u root ($USER will be root, not the original USER).
How do I run the script as root but also run certain commands in the script as the default logged in user so I don't have to put in the password or do chmod to change permissions?
You need the non-evaluated user in some variable.
How you want to do this depends on your actual use case.
You can look at:
Nasty temp file:
echo "$USER" > /tmp/thatsme.tmp
su -
# Hmm, now hope nobody has changed the tmpfile doing the same trick
orguser=$(cat /tmp/thatsme.tmp)
rm /tmp/thatsme.tmp
Keep environment
export orguser="$USER"
su # Not su -
echo "orguser=${orguser}"
Proces ps -ef and look for original user on the same tty you are on. (not recommended)
Call su - -c script additional parameter and change your master script that it pulls the user from $1.
Within your bash script you'll need to use the 'su' command to switch user, then the -c command with your needed command/script.
If you run as root you won't need to put in the $USER password.
Example: su $USER -c "command"

Getting correct $HOME directory in bash on google cloud

My bash script has the following code and i executed it on google cloud compute engine.
mv $HOME/openvpn-2.4.0/ /etc/openvpn
The problem here is that $HOME get expanded to /root instead of /home/myusername.
echo $HOME at command prompt gives /home/myusername as expected.
What am i doing wrong here ?
Edit 1
If i execute the bash script with sudo the $HOME variable gives /root , but when i execute the script without sudo the $HOME variable gives /home/myusername as expected on google cloud
When you run the bash script with sudo, it runs the script as root user, so the $HOME variable gives /root.
One option is to pass the $HOME environment variable as a command line option to your bash script. You can then access the value of this variable inside the bash script as $1.
I used $SUDO_USER to find the home directory
HOME=$(getent passwd $SUDO_USER | cut -d: -f6)

How to get $HOME directory when switching to a different user in bash?

I need to execute part of a bash script as a different user, and inside that user's $HOME directory. However, I'm not sure how to determine this variable. Switching to that user and calling $HOME does not provide the correct location:
# running script as root, but switching to a different user...
su - $different_user
echo $HOME
# returns /root/ but should be /home/myuser
Update:
It appears that the issue is with the way that I am trying to switch users in my script:
$different_user=deploy
# create user
useradd -m -s /bin/bash $different_user
echo "Current user: `whoami`"
# Current user: root
echo "Switching user to $different_user"
# Switching user to deploy
su - $different_user
echo "Current user: `whoami`"
# Current user: root
echo "Current user: `id`"
# Current user: uid=0(root) gid=0(root) groups=0(root)
sudo su $different_user
# Current user: root
# Current user: uid=0(root) gid=0(root) groups=0(root)
What is the correct way to switch users and execute commands as a different user in a bash script?
Update: Based on this question's title, people seem to come here just looking for a way to find a different user's home directory, without the need to impersonate that user.
In that case, the simplest solution is to use tilde expansion with the username of interest, combined with eval (which is needed, because the username must be given as an unquoted literal in order for tilde expansion to work):
eval echo "~$different_user" # prints $different_user's home dir.
Note: The usual caveats regarding the use of eval apply; in this case, the assumption is that you control the value of $different_user and know it to be a mere username.
By contrast, the remainder of this answer deals with impersonating a user and performing operations in that user's home directory.
Note:
Administrators by default and other users if authorized via the sudoers file can impersonate other users via sudo.
The following is based on the default configuration of sudo - changing its configuration can make it behave differently - see man sudoers.
The basic form of executing a command as another user is:
sudo -H -u someUser someExe [arg1 ...]
# Example:
sudo -H -u root env # print the root user's environment
Note:
If you neglect to specify -H, the impersonating process (the process invoked in the context of the specified user) will report the original user's home directory in $HOME.
The impersonating process will have the same working directory as the invoking process.
The impersonating process performs no shell expansions on string literals passed as arguments, since no shell is involved in the impersonating process (unless someExe happens to be a shell) - expansions by the invoking shell - prior to passing to the impersonating process - can obviously still occur.
Optionally, you can have an impersonating process run as or via a(n impersonating) shell, by prefixing someExe either with -i or -s - not specifying someExe ... creates an interactive shell:
-i creates a login shell for someUser, which implies the following:
someUser's user-specific shell profile, if defined, is loaded.
$HOME points to someUser's home directory, so there's no need for -H (though you may still specify it)
The working directory for the impersonating shell is the someUser's home directory.
-s creates a non-login shell:
no shell profile is loaded (though initialization files for interactive nonlogin shells are; e.g., ~/.bashrc)
Unless you also specify -H, the impersonating process will report the original user's home directory in $HOME.
The impersonating shell will have the same working directory as the invoking process.
Using a shell means that string arguments passed on the command line MAY be subject to shell expansions - see platform-specific differences below - by the impersonating shell (possibly after initial expansion by the invoking shell); compare the following two commands (which use single quotes to prevent premature expansion by the invoking shell):
# Run root's shell profile, change to root's home dir.
sudo -u root -i eval 'echo $SHELL - $USER - $HOME - $PWD'
# Don't run root's shell profile, use current working dir.
# Note the required -H to define $HOME as root`s home dir.
sudo -u root -H -s eval 'echo $SHELL - $USER - $HOME - $PWD'
What shell is invoked is determined by "the SHELL environment variable if it is set or the shell as specified in passwd(5)" (according to man sudo). Note that with -s it is the invoking user's environment that matters, whereas with -i it is the impersonated user's.
Note that there are platform differences regarding shell-related behavior (with -i or -s):
sudo on Linux apparently only accepts an executable or builtin name as the first argument following -s/-i, whereas OSX allows passing an entire shell command line; e.g., OSX accepts sudo -u root -s 'echo $SHELL - $USER - $HOME - $PWD' directly (no need for eval), whereas Linux doesn't (as of sudo 1.8.95p).
Older versions of sudo on Linux do NOT apply shell expansions to arguments passed to a shell; for instance, with sudo 1.8.3p1 (e.g., Ubuntu 12.04), sudo -u root -H -s echo '$HOME' simply echoes the string literal "$HOME" instead of expanding the variable reference in the context of the root user. As of at least sudo 1.8.9p5 (e.g., Ubuntu 14.04) this has been fixed. Therefore, to ensure expansion on Linux even with older sudo versions, pass the the entire command as a single argument to eval; e.g.: sudo -u root -H -s eval 'echo $HOME'. (Although not necessary on OSX, this will work there, too.)
The root user's $SHELL variable contains /bin/sh on OSX 10.9, whereas it is /bin/bash on Ubuntu 12.04.
Whether the impersonating process involves a shell or not, its environment will have the following variables set, reflecting the invoking user and command: SUDO_COMMAND, SUDO_USER, SUDO_UID=, SUDO_GID.
See man sudo and man sudoers for many more subtleties.
Tip of the hat to #DavidW and #Andrew for inspiration.
In BASH, you can find a user's $HOME directory by prefixing the user's login ID with a tilde character. For example:
$ echo ~bob
This will echo out user bob's $HOME directory.
However, you say you want to be able to execute a script as a particular user. To do that, you need to setup sudo. This command allows you to execute particular commands as either a particular user. For example, to execute foo as user bob:
$ sudo -i -ubob -sfoo
This will start up a new shell, and the -i will simulate a login with the user's default environment and shell (which means the foo command will execute from the bob's$HOME` directory.)
Sudo is a bit complex to setup, and you need to be a superuser just to be able to see the shudders file (usually /etc/sudoers). However, this file usually has several examples you can use.
In this file, you can specify the commands you specify who can run a command, as which user, and whether or not that user has to enter their password before executing that command. This is normally the default (because it proves that this is the user and not someone who came by while the user was getting a Coke.) However, when you run a shell script, you usually want to disable this feature.
For the sake of an alternative answer for those searching for a lightweight way to just find a user's home dir...
Rather than messing with su hacks, or bothering with the overhead of launching another bash shell just to find the $HOME environment variable...
Lightweight Simple Homedir Query via Bash
There is a command specifically for this: getent
getent passwd someuser | cut -f6 -d:
getent can do a lot more... just see the man page. The passwd nsswitch database will return the user's entry in /etc/passwd format. Just split it on the colon : to parse out the fields.
It should be installed on most Linux systems (or any system that uses GNU Lib C (RHEL: glibc-common, Deb: libc-bin)
The title of this question is How to get $HOME directory of different user in bash script? and that is what people are coming here from Google to find out.
There is a safe way to do this!
on Linux/BSD/macOS/OSX without sudo or root
user=pi
user_home=$(bash -c "cd ~$(printf %q $USER) && pwd")
NOTE: The reason this is safe is because bash (even versions prior to 4.4) has its own printf function that includes:
%q quote the argument in a way that can be reused as shell input
See: help printf
Compare the how other answers here respond to code injection
# "ls /" is not dangerous so you can try this on your machine
# But, it could just as easily be "sudo rm -rf /*"
$ user="root; ls /"
$ printf "%q" "$user"
root\;\ ls\ /
# This is what you get when you are PROTECTED from code injection
$ user_home=$(bash -c "cd ~$(printf "%q" "$user") && pwd"); echo $user_home
bash: line 0: cd: ~root; ls /: No such file or directory
# This is what you get when you ARE NOT PROTECTED from code injection
$ user_home=$(bash -c "cd ~$user && pwd"); echo $user_home
bin boot dev etc home lib lib64 media mnt ono opt proc root run sbin srv sys tmp usr var /root
$ user_home=$(eval "echo ~$user"); echo $user_home
/root bin boot dev etc home lib lib64 media mnt ono opt proc root run sbin srv sys tmp usr var
on Linux/BSD/macOS/OSX as root
If you are doing this because you are running something as root then you can use the power of sudo:
user=pi
user_home=$(sudo -u $user sh -c 'echo $HOME')
on Linux/BSD (but not modern macOS/OSX) without sudo or root
If not, the you can get it from /etc/passwd. There are already lots of examples of using eval and getent, so I'll give another option:
user=pi
user_home=$(awk -v u="$user" -v FS=':' '$1==u {print $6}' /etc/passwd)
I would really only use that one if I had a bash script with lots of other awk oneliners and no uses of cut. While many people like to "code golf" to use the fewest characters to accomplish a task, I favor "tool golf" because using fewer tools gives your script a smaller "compatibility footprint". Also, it's less man pages for your coworker or future-self to have to read to make sense of it.
You want the -u option for sudo in this case. From the man page:
The -u (user) option causes sudo to run the specified command as a user other than root.
If you don't need to actually run it as them, you could move to their home directory with ~<user>. As in, to move into my home directory you would use cd ~chooban.
So you want to:
execute part of a bash script as a different user
change to that user's $HOME directory
Inspired by this answer, here's the adapted version of your script:
#!/usr/bin/env bash
different_user=deploy
useradd -m -s /bin/bash "$different_user"
echo "Current user: $(whoami)"
echo "Current directory: $(pwd)"
echo
echo "Switching user to $different_user"
sudo -u "$different_user" -i /bin/bash - <<-'EOF'
echo "Current user: $(id)"
echo "Current directory: $(pwd)"
EOF
echo
echo "Switched back to $(whoami)"
different_user_home="$(eval echo ~"$different_user")"
echo "$different_user home directory: $different_user_home"
When you run it, you should get the following:
Current user: root
Current directory: /root
Switching user to deploy
Current user: uid=1003(deploy) gid=1003(deploy) groups=1003(deploy)
Current directory: /home/deploy
Switched back to root
deploy home directory: /home/deploy
This works in Linux. Not sure how it behaves in other *nixes.
getent passwd "${OTHER_USER}"|cut -d\: -f 6
I was also looking for this, but didn't want to impersonate a user to simply acquire a path!
user_path=$(grep $username /etc/passwd|cut -f6 -d":");
Now in your script, you can refer to $user_path in most cases would be /home/username
Assumes: You have previously set $username with the value of the intended users username.
Source: http://www.unix.com/shell-programming-and-scripting/171782-cut-fields-etc-passwd-file-into-variables.html
Quick and dirty, and store it in a variable:
USER=somebody
USER_HOME="$(echo -n $(bash -c "cd ~${USER} && pwd"))"
I was struggling with this question because I was looking for a way to do this in a bash script for OS X, hence /etc/passwd was out of the question, and my script was meant to be executed as root, therefore making the solutions invoking eval or bash -c dangerous as they allowed code injection into the variable specifying the username.
Here is what I found. It's simple and doesn't put a variable inside a subshell. However it does require the script to be ran by root as it sudos into the specified user account.
Presuming that $SOMEUSER contains a valid username:
echo "$(sudo -H -u "$SOMEUSER" -s -- "cd ~ && pwd")"
I hope this helps somebody!
If the user doesn't exist, getent will return an error.
Here's a small shell function that doesn't ignore the exit code of getent:
get_home() {
local result; result="$(getent passwd "$1")" || return
echo $result | cut -d : -f 6
}
Here's a usage example:
da_home="$(get_home missing_user)" || {
echo 'User does NOT exist!'; exit 1
}
# Now do something with $da_home
echo "Home directory is: '$da_home'"
The output of getent passwd username can be parsed with a Bash regular expression
OTHER_HOME="$(
[[ "$(
getent \
passwd \
"${OTHER_USER}"
)" =~ ([^:]*:){5}([^:]+) ]] \
&& echo "${BASH_REMATCH[2]}"
)"
If you have sudo active, just do:
sudo su - admin -c "echo \$HOME"
NOTE: replace admin for the user you want to get the home directory

Resources