I created a service based on this code Is it possible to run a Python script as a service in Windows? If possible, how?
But when i run the code I can only run it as a service and not a normal process.
Is it possible to create a script that when it is run by an admin it runs as a service, but when its activated without admin privileges it runs as a normal process?
1 Answers
With win32service
(some docs here) you can also get the user info by calling the method GetUserObjectInformation
, with differente type
parameters to get one of UOI_FLAGS,UOI_NAME, UOI_TYPE, or UOI_USER_SID
. The complete list of user info types can be found here.
To have a look just print the info somewhere on your program, like the snippet below. If the user name is all that you need win32api
will get you there easier.
print win32api.GetUserName()
print win32service.GetUserObjectInformation( win32service.OpenInputDesktop(0,0,1), 4)
# or simply:
print win32service.GetUserObjectInformation( win32service.GetProcessWindowStation(), 4)
Finally, in order to get the privileges directly you can use win32net
like so:
win32net.NetUserGetInfo(None, win32api.GetUserName() , 11 )['priv']
This will return an int which maps to:
- win32netcon.USER_PRIV_GUEST (0)
- win32netcon.USER_PRIV_USER (1)
- win32netcon.USER_PRIV_ADMIN (2)
In your program you can check if win32net.NetUserGetInfo(None, win32api.GetUserName() , 11 )['priv'] == win32netcon.USER_PRIV_ADMIN
to launch it as a service or not.
For more information on the extensions you can find a brief reference here.

- 5,509
- 3
- 31
- 46
-
I found some `not yet implemented` functionality. Hope this info is enough – rll Nov 23 '15 at 12:36
-
why would I need a users name? – yuval Nov 23 '15 at 13:39
-
Doesn't work. When i run the service without admin it runs it as a normal process successfully. But when i start it as a service i get an error "The Windows ____ service on local computer started and then stopped. Some services stop automatically if they are not in use by other services or programs" – yuval Nov 24 '15 at 11:15
-
Well, it looks like the solution works for the part you asked (you can differentiate the type of user and launch not as a service if the user is not admin). I do understand that you could launch it as a service before, but that error does not explain anything at all. As much as I can see it is not a problem of differentiating the user. Can you build a minimal working example or at least post the code you wrote? – rll Nov 24 '15 at 11:25
-
win32net.NetUserGetInfo(None, win32api.GetUserName() , 11 )['priv'] always return 2L, admin or not – yuval Nov 24 '15 at 12:46
-
You must be doing something wrong regarding your users, I just created a standar user on my pc and verified that `priv` is indeed 1L – rll Nov 24 '15 at 15:35