5

現在のユーザーが管理者である場合にのみ、アプリケーションの特定の機能にアクセスできるようにしたい。

WindowsでPythonを使用して、現在のユーザーがローカルのAdministratorsグループに属しているかどうかを確認するにはどうすればよいですか?

4

3 に答える 3

6

あなたはこれを試すことができます:

import ctypes
print ctypes.windll.shell32.IsUserAnAdmin()
于 2010-03-15T16:10:06.003 に答える
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'))

もちろん、あなたの場合、「SOME_GROUP」は「管理者」になります

于 2016-04-29T19:48:19.150 に答える
1

Vlad Bezdenにクレジットを与えたいと思います。なぜなら、彼がwin32netモジュールを使用しなければ、この答えは存在しなかったからです。

ユーザーがUACを超えて管理者として行動できるかどうかを本当に知りたい場合は、次のようにすることができます。また、必要に応じて、現在のユーザーが所属するグループも一覧表示されます。ほとんどの(すべて?)言語設定で
動作します。ローカルグループは、通常は「Admin」で開始する必要があります... (一部の設定が異なるかどうか誰かが知っていますか?)

このコードスニペットを使用するにはpywin32、モジュールをインストールする必要があります。まだインストールしていない場合は、PyPIから入手できます。pip install pywin32


知っておくべき重要事項os.getlogin()一部のユーザー/コーダーにとって、この関数はWindowsオペレーティングシステム上のpython3.1以降でのみ使用可能であることが重要な場合があります... python3.1ドキュメント

win32netリファレンス

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.

ああ、どこfrom time import sleepsleep(10)

独自のインポート/コードを挿入...

于 2018-05-07T08:50:12.253 に答える