None of the above worked in my case [scroll down to the actual solution].
The problem I'm getting with all solutions is the wrong username when running commands with sudo
:
psutil
soulution:
$ python3
>>> import psutil
>>> psutil.Process[].username[]
'ubuntu' # OK!
$ sudo su
$ python3
>>> import psutil
>>> psutil.Process[].username[]
'root' # OK!
$ sudo python3
>>> import psutil
>>> psutil.Process[].username[]
'root' # WRONG, should be ubuntu!
getpass
solution:
$ python3
>>> import getpass
>>> getpass.getuser[]
'ubuntu' # OK!
$ sudo su
$ python3
>>> import getpass
>>> getpass.getuser[]
'root' # OK!
$ sudo python3
>>> import getpass
>>> getpass.getuser[]
'root' # WRONG, should be ubuntu!
pwd
+os.getuid
solution:
$ python3
>>> import os, pwd
>>> pwd.getpwuid[ os.getuid[] ][ 0 ]
'ubuntu' # OK!
$ sudo su
$ python3
>>> import os, pwd
>>> pwd.getpwuid[ os.getuid[] ][ 0 ]
'root' # OK!
$ sudo python3
>>> import getpass
>>> getpass.getuser[]
'root' # WRONG, should be ubuntu!
os.getlogin
works a bit different, but still wrong:
$ python3
>>> import os
>>> os.getlogin[]
'ubuntu' # OK!
$ sudo su
$ python3
>>> import os
>>> os.getlogin[]
'ubuntu' # WRONG, should be root!
$ sudo python3
>>> import os
>>> os.getlogin[]
'ubuntu' # OK!
os.getenv
gives the same results:
$ python3
>>> import os
>>> os.getenv['SUDO_USER', os.getenv['USER']]
'ubuntu' # OK!
$ sudo su
$ python3
>>> import os
>>> os.getenv['SUDO_USER', os.getenv['USER']]
'ubuntu' # WRONG, should be root!
$ sudo python3
>>> import os
>>> os.getenv['SUDO_USER', os.getenv['USER']]
'ubuntu' # OK!
Switching SUDO_USER
and USER
gives the wrong result in sudo python3
case.
Actual solution [non-portable]
Solution is a bit tricky and rely on the default root home directory location but works for all cases:
$ python3
>>> import os
>>> 'root' if os.path.expanduser['~'] == '/root' else os.getenv['SUDO_USER', os.getenv['USER']]
'ubuntu' # OK!
$ sudo su
$ python3
>>> import os
>>> 'root' if os.path.expanduser['~'] == '/root' else os.getenv['SUDO_USER', os.getenv['USER']]
'root' # OK!
$ sudo python3
>>> import os
>>> 'root' if os.path.expanduser['~'] == '/root' else os.getenv['SUDO_USER', os.getenv['USER']]
'ubuntu' # OK!