I stumbled across a difference in the way sudo
alters env
variables between CentOS 7.3 and CentOS 7.4.
Here is a script I have run on CentOS 7.3 and 7.4:
#!/bin/bash
env | grep USER
sudo env | grep USER
unset USERNAME
env | grep USER
sudo env | grep USER
On CentOS 7.3 this gives (formatted):
USER=gncs
USERNAME=gncs
[sudo] password for gncs:
USERNAME=gncs
USER=root
SUDO_USER=gncs
USER=gncs
USER=root
USERNAME=root
SUDO_USER=gncs
On CentOS 7.4 this gives (formatted):
USER=gncs
USERNAME=gncs
[sudo] password for gncs:
USERNAME=gncs
USER=gncs # !!!
SUDO_USER=gncs
USER=gncs
USER=root
USERNAME=root
SUDO_USER=gncs
Why is USER
still gncs
when I run env
with sudo
on CentOS 7.4?
Once I unset the USERNAME
variable the behavior is the same.
I came across this problem when running the following python program with sudo
:
import getpass
getpass.getuser()
Under Centos 7.3 it returns root
, under 7.4 gncs
.
I believe this is related to the environment variables mentioned above.
Additional information:
$ sudo --version
Sudo version 1.8.19p2
Sudoers policy plugin version 1.8.19p2
Sudoers file grammar version 45
Sudoers I/O plugin version 1.8.19p2
$ sudo grep -r env /etc/sudo*
[sudo] password for gncs:
/etc/sudoers:# is already set when the the env_reset option is enabled, so
/etc/sudoers:# env_reset is disabled or HOME is present in the env_keep list.
/etc/sudoers:Defaults env_reset
/etc/sudoers:Defaults env_keep = "COLORS DISPLAY HOSTNAME HISTSIZE KDEDIR LS_COLORS"
/etc/sudoers:Defaults env_keep += "MAIL PS1 PS2 QTDIR USERNAME LANG LC_ADDRESS LC_CTYPE"
/etc/sudoers:Defaults env_keep += "LC_COLLATE LC_IDENTIFICATION LC_MEASUREMENT LC_MESSAGES"
/etc/sudoers:Defaults env_keep += "LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER LC_TELEPHONE"
/etc/sudoers:Defaults env_keep += "LC_TIME LC_ALL LANGUAGE LINGUAS _XKB_CHARSET XAUTHORITY"
/etc/sudoers:# Adding HOME to env_keep may enable a user to run unrestricted
/etc/sudoers:# Defaults env_keep += "HOME"
Best Answer
There have been changes to the sudo program in CentOS 7.4. The question really is the user wants to get the OS username in a python code. All the methods seem to be dependent on the environment variables so it might not be working in all scenarios.
You could try these options to make it at least work on CentOS 7.3 and 7.4
Note: I would have added this as a comment but I have just started answering questions and do not have enough reputation to add it as a comment.