If I execute print os.environ
without pkexec I get lots of useful system environment variables, however, once I execute with, most of them are gone. How can I get them back with using pkexec? I understand there's a workaround using sudo but haven't found one yet for pkexec
Asked
Active
Viewed 1,803 times
2

answerSeeker
- 2,692
- 4
- 38
- 76
-
3Possible duplicate of [How to keep Environment Variables when Using SUDO](http://stackoverflow.com/questions/8633461/how-to-keep-environment-variables-when-using-sudo) – Josh Lee Mar 22 '17 at 18:42
-
The `man` page says `-E, --preserve-env Indicates to the security policy that the user wishes to pre‐ serve their existing environment variables. The security policy may return an error if the user does not have permis‐ sion to preserve the environment.` – tdelaney Mar 22 '17 at 18:43
-
@JoshLee - that's a good reference answer. Would you like to close this as a dup? – tdelaney Mar 22 '17 at 18:45
-
Wait I will edit my question. It's different alright – answerSeeker Mar 22 '17 at 18:47
-
I don't want to go and modify the sudoers file because I'd preferably like a general solution that works on different linux machines – answerSeeker Mar 22 '17 at 18:55
-
[pkexec doc](https://www.freedesktop.org/software/polkit/docs/0.105/pkexec.1.html) says: `The environment that PROGRAM will run it, will be set to a minimal known and safe environment in order to avoid injecting code through LD_LIBRARY_PATH or similar mechanisms.`. `pkexec` is a policykit thing... I have no idea if you can add env to policies. You may have luck asking this question on serverfault.com. – tdelaney Mar 22 '17 at 19:01
-
1@tselaney this is not a dup sudo != pkexec – wheredidthatnamecomefrom Apr 28 '19 at 18:39
2 Answers
5
In short, you can't. From the pkexec
man page:
The environment that PROGRAM will run in will be set to a minimal known and safe environment in order to avoid injecting code through LD_LIBRARY_PATH or similar mechanisms. In addition the PKEXEC_UID environment variable is set to the user id of the process invoking pkexec.
You can cause pkexec
to retain some environmental variables (i.e. to allow X11 programs to work by retaining $DISPLAY
and $XAUTHORITY
) using the org.freedesktop.policykit.exec.allow_gui
annotation. However, retaining all of the environmental variables appears to be a deliberate rejected decision.

Matthew Cole
- 602
- 5
- 21
-
1BTW, if interesting to anyone, I use `pkexec`ed app that need UI access like this: `pkexec env DISPLAY=$DISPLAY WAYLAND_DISPLAY=$WAYLAND_DISPLAY XDG_SESSION_TYPE=$XDG_SESSION_TYPE XDG_RUNTIME_DIR=$XDG_RUNTIME_DIR myapp` – Guss Jan 05 '23 at 13:30
1
If you only need to keep a few environment variables, you can always preserve them using env
:
pkexec bash -c 'echo $PATH'
/usr/sbin:/usr/bin:/sbin:/bin:/root/bin
pkexec env PATH=$PATH bash -c 'echo $PATH'
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/local/games:/usr/games

Dmitry Grigoryev
- 3,156
- 1
- 25
- 53