I'm executing a python script as root with pkexec and I'm using working_dir = os.getenv('HOME') to get the username but it always returns root instead of test1 which is the current user. How can I get the user that ran pkexec instead?

I already tried print os.environ["SUDO_USER"] but that fails since it's not being executed directly with sudo. I am on trusty now but behaves the same in 16.04.

  • 1
    AFAIK the only environment variable inherited from the invoking user is PKEXEC_UID, so you'd need to find a (non evil) way to derive the home directory from that – steeldriver Mar 14 '17 at 2:05
  • Thanks, using print os.environ["PKEXEC_UID"] I managed to get the normal user's uid. I just need to get the name of the user from the uid and this should solve my problem which is less complicated – answerSeeker Mar 14 '17 at 2:07

I fixed it like this:

import pwd
import os

user = pwd.getpwuid(int(os.environ["PKEXEC_UID"])).pw_name
working_dir = '/home/{}'.format(user)

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.