Issue
[root@hostname ~]# python script.py # allow this
[user@hostname ~]$ sudo python script.py # deny this
[user@hostname ~]$ sudo -E python script.py # deny this
[user@hostname ~]$ sudo PATH=$PATH python script.py # deny this
[user@hostname ~]$ python script.py # kindly refuse this
I'm trying to achieve the behavior above. Read further if you care why or if the example isn't sufficient enough. Sorry for the sharp tongue, but most of my Stack Exchange questions get hostile questions back instead of answers.
This question arises from requiring an admin to run my script, but the nature of the script requires root
's environment variables (and not sudo
's).
I've given this some thorough research... below is from this answer
if os.geteuid() == 0:
pass # sufficient to determine if elevated privileges
But then I started needing to access PATH
inside of my script. I noticed that
sudo -E env | grep PATH; env | grep PATH
prints different PATH
values. I found it was because of the security policy on PATH
. I also found the workaround to PATH
is sudo PATH=$PATH ...
However, it's not the only policy protected environment variable, and at that point, why push this enumeration of environment variables on the script user? It seems that requiring root
explicitly is the best approach, and just warn the admin to use root
explicitly from within the script otherwise.
Is there such a way to distinguish between root
and sudo
with Python?
Solution
Despite the reasons discussed to not pursue this solution, I actually did find it for others wondering if it's possible.
[user@hostname ~]$ sudo python
>>> import os
>>> os.environ["SUDO_UID"] # UID of user running sudo
'uid'
And when logged in as root...
[root@hostname ~]# python
>>> import os
>>> try:
... uid = os.environ["SUDO_UID"]
raise AssertionError("Ran with sudo")
... except KeyError, e:
... ... # SUDO_UID, SUDO_USER, etc. not set without sudo
I also found a way to access root
's PATH
just running with sudo
.
path = os.popen("su - -c env | grep ^PATH= | cut -d'=' -f2-").read().strip()
I think I like this solution better than relying on how my script is ran.
Answered By - user7851115
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.