win32net unable to delete local user from group

1k Views Asked by At

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.

2

There are 2 best solutions below

0
On BEST ANSWER

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"])

1
On

Ok...

This has been overthought. The answer is to use subprocess or some method to invoke a command line statement and the command line statement is...

net localgroup administrators "DOMAIN\Domain Users" /delete

I just did the command in a cmd prompt and it ran successfully. Classic.