Search code examples
pythonwinapiactive-directory-group

win32net unable to delete local user from group


Having a problem with a simple simple task... find users that don't belong in the local administrators group and remove them...

import win32net


def BAD_DomainUsers(computer):
    x = win32net.NetLocalGroupGetMembers(computer,"Administrators", 2)
    for i in x[0]:
        if i["domainandname"] == r"DOMAIN\Domain Users":
            return True
    return False

def Remove_BadUsers(computer):
    win32net.NetLocalGroupDelMembers(computer, "Administrators", r"DOMAIN\Domain Users")

computer = "P04213"

if BAD_DomainUsers(computer):  Remove_BadUsers(computer)

This returns the error:

    win32net.NetLocalGroupDelMembers(computer, "Administrators", r"DOMAIN\Domain Users")
pywintypes.error: (1387, 'NetLocalGroupDelMembers', 'A member could not be added to or removed from the local group because the member does not exist.')

But when I enumerate the Administrators group, sure enough DOMAIN\Domain Users is a member... or else it would not call the Remove_BadUsers function. There must be SOMETHING I am missing, but I can't figure it out.


Solution

  • I'm well aware that this post is old, but it is the top result in searches and I hate answers that don't answer the question posed. So, here is the answer:

    win32net.NetLocalGroupDelMembers expects a list of strings for it's third argument e.g. win32net.NetLocalGroupDelMembers(computer, "Administrators", [r"DOMAIN\Domain Users"])