Using CreateProcessAsUser in python does not pass the user's environment to the created process

1.4k views Asked by At

First thank you for your time reading this question.

I start an app executable (lets call it MyApp.exe) successfully from my windows service under the Interactive user using the following code:

#MyWindowsService.py

console_session_id = win32ts.WTSGetActiveConsoleSessionId()
console_user_token = win32ts.WTSQueryUserToken(console_session_id)

my_app_path= os.path.normpath(r"/Path\to\MyApp.exe")
startup = win32process.STARTUPINFO()
priority = win32con.NORMAL_PRIORITY_CLASS
handle, thread_id ,pid, tid = win32process.CreateProcessAsUser(console_user_token, my_app_path, None, None, None, True, priority, None, None, startup)

From inside MyApp I need to get the environment paths that belong to the interactive user. For example I use the following code to get the path for user's %appdata%:

#MyApp.py

user_app_data_path = os.getenv('APPDATA')

It should return:

C:\Users\ Interactive-user-name \AppData\Roaming

However the returned value is:

C:\Windows\System32\config\systemprofile\AppData\Roaming

Which means although MyApp.exe is started under interactive user's name, it gets the environment for SYSTEM user that the windows service is running under.

My question is how I can get the environment paths that belong to the user not system.

Many thank,

P.S. I am using py2exe to convert MyApp and Windows service into executables.

1

There are 1 answers

1
Navid On BEST ANSWER

I found the answer, in case any one is interested:

According to this if the environment is not explicitly specified, the process inherits the environment of the parent. Using this one can get the environment and pass it on to CreateProcessAsUser.

Simply follow the environment word in the following code.

#MyWindowsService.py

console_session_id = win32ts.WTSGetActiveConsoleSessionId()
console_user_token = win32ts.WTSQueryUserToken(console_session_id)

my_app_path= os.path.normpath(r"/Path\to\MyApp.exe")
startup = win32process.STARTUPINFO()
priority = win32con.NORMAL_PRIORITY_CLASS
environment = win32profile.CreateEnvironmentBlock(console_user_token, False)
handle, thread_id ,pid, tid = win32process.CreateProcessAsUser(console_user_token, my_app_path, None, None, None, True, priority, environment, None, startup)