Skip to content

Instantly share code, notes, and snippets.

@leewinder
Last active September 29, 2016 21:41
Show Gist options
  • Save leewinder/54f59ba57e68a53cf360f12e88f620d3 to your computer and use it in GitHub Desktop.
Save leewinder/54f59ba57e68a53cf360f12e88f620d3 to your computer and use it in GitHub Desktop.
Accessing the local users environment variables even when running via sudo (Mac only)
# Imports
import subprocess
import json
import os
#
# Appends a gven users environment variables to the current process
#
def __append_users_environment_variables(user_name):
# Load in the environment variables for this user
profile_to_load = '/Users/{0}/.bash_profile'.format(user_name)
env_to_json = 'import os, json; print(json.dumps(dict(os.environ)))'
# Append the environment variables into os.environ
environ_json = subprocess.check_output('. {} && python -c "{}"'.format(profile_to_load, env_to_json), shell=True, env={})
os.environ.update(json.loads(environ_json.decode('utf8')))
#
# Finds the name of the local user regardless of whether it was run as sudo or not
#
def find_local_user():
# Track our current names
sudo_user = None
local_user = None
# Check our user and our sudo user
if 'SUDO_USER' in os.environ:
sudo_user = os.environ['SUDO_USER']
if 'USER' in os.environ:
local_user = os.environ['USER']
# If we have a sudo user, we use that user
if sudo_user != None:
local_user = sudo_user
# Return our user
return local_user
#
# Updates the environment variables of the local user if they are run as sudo
#
def update_local_environment_variables():
# Get our username rather than Sudo or not and append their environment variables
user_name = find_local_user()
if user_name != None:
__append_users_environment_variables(user_name)
@leewinder
Copy link
Author

Calling update_local_environment_variables will result in the local users environment variables (if stored in .bash_profile) be available to the caller, even if the script was called using sudo.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment