简体   繁体   中英

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

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?

You could try this :

import ctypes
print ctypes.windll.shell32.IsUserAnAdmin()
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'

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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM