Wednesday, October 24, 2012

sudo -s on RHEL 6 doesn't preserve HOME

Solution:

If you're the only one using this machine, the easiest fix is to run this command as root:
visudo

and then add this line to the sudoers file:
Defaults env_keep=HOME

If this is a shared computer and you aren't at liberty to change the sudoers file, you can add this code to .bashrc in your home directory. be sure to log out and back in for it to take effect:

# hack to preserve home when using sudo -s on rhel 6
if [[ `cat /etc/*release | grep "release 6"` ]]; then
    sudo() {
        if [[ $@ == "-s" ]]; then
            sudo bash -c "HOME=$HOME; exec bash"
        else
            command sudo "$@";
        fi;
    }
fi;


Details:

In linux, if I want to become root but keep my user's environment (home, aliases, etc), I normally use sudo -s:
[user@computer ~]$ sudo -s
[root@computer ~]# echo $HOME
/home/user


and if I want to become root and use root's environment, I'll use sudo -i:
[user@computer ~]$ sudo -i
[root@computer ~]# echo $HOME
/root


The above works on Ubuntu, and all versions of RHEL up to 5 (the same probably goes for CentOS). however, I recently noticed that RHEL 6 , my home variable isn't preserved when using sudo -s:
[user@computer ~]$ sudo -s
[root@computer user]# echo $HOME
/root


The most frustrating thing is that because of this, it seems like my .bashrc wasn't being called, and so I didn't have access to my aliases any more.

It seems like the cause of this is that the default in RHEL 6 is not to preserve the home variable. you can see this running this command as root:
sudo -V

If you look under the list of "Environment variables to preserve," you'll notice that in RHEL 5 HOME is listed, but in RHEL 6 it isn't.

0 comments:

Post a Comment