Determine if current user is in Administrators group (Windows/Python)
Asked Answered
T

3

5

I want certain functions in my application to only be accessible if the current user is an administrator.

How can I determine if the current user is in the local Administrators group using Python on Windows?

Talc answered 15/3, 2010 at 15:46 Comment(0)
B
6

You could try this:

import ctypes
print ctypes.windll.shell32.IsUserAnAdmin()
Bingle answered 15/3, 2010 at 16:10 Comment(2)
IT doesn't work when UAC is activated, it seems that this function checks the process rights.Galligaskins
IsUserAnAdmin() only works with Windows XP. It won't work correctly on later editions of Windows.Menides
Q
2
import win32net


def if_user_in_group(group, member):
    members = win32net.NetLocalGroupGetMembers(None, group, 1)
    return member.lower() in list(map(lambda d: d['name'].lower(), members[0]))  


# Function usage
print(if_user_in_group('SOME_GROUP', 'SOME_USER'))

Of course in your case 'SOME_GROUP' will be 'administrators'

Quintic answered 29/4, 2016 at 19:48 Comment(0)
B
1

I'd like to give some credit to Vlad Bezden, becuase without his use of the win32net module this answer here would not exist.

If you really want to know if the user has the ability to act as an admin past UAC you can do the following. It also lists the groups the current user is in, if needed.
It will work on most (all?) language set-ups.
The local group just hast to start with "Admin", which it usually does...
(Does anyone know if some set-ups will be different?)

To use this code snippet you'll need to have pywin32 module installed, if you don't have it yet you can get it from PyPI: pip install pywin32

IMPORTANT TO KNOW:
It may be important to some users / coders that the function os.getlogin() is only available since python3.1 on Windows operating systems... python3.1 Documentation

win32net Reference

from time import sleep
import os
import win32net

if 'logonserver' in os.environ:
    server = os.environ['logonserver'][2:]
else:
    server = None

def if_user_is_admin(Server):
    groups = win32net.NetUserGetLocalGroups(Server, os.getlogin())
    isadmin = False
    for group in groups:
        if group.lower().startswith('admin'):
            isadmin = True
    return isadmin, groups


# Function usage
is_admin, groups = if_user_is_admin(server)

# Result handeling
if is_admin == True:
    print('You are a admin user!')
else:
    print('You are not an admin user.')
print('You are in the following groups:')
for group in groups:
    print(group)

sleep(10)

# (C) 2018 DelphiGeekGuy@Stack Overflow
# Don't hesitate to credit the author if you plan to use this snippet for production.

Oh and WHERE from time import sleep and sleep(10):

INSERT own imports/code...

Butyrate answered 7/5, 2018 at 8:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.