def get_user_groups(name, sid=False): ''' Get the groups to which a user belongs Args: name (str): The user name to query sid (bool): True will return a list of SIDs, False will return a list of group names Returns: list: A list of group names or sids ''' groups = [] if name.upper() == 'SYSTEM': # 'win32net.NetUserGetLocalGroups' will fail if you pass in 'SYSTEM'. groups = ['SYSTEM'] else: try: groups = win32net.NetUserGetLocalGroups(None, name) except win32net.error as exc: if exc.winerror == 5: # Try without LG_INCLUDE_INDIRECT flag, because the user might # not have permissions for it groups = win32net.NetUserGetLocalGroups(None, name, 0) else: raise if not sid: return groups ret_groups = [] for group in groups: ret_groups.append(get_sid_from_name(group)) return ret_groups
def get_user_groups(name, sid=False): """ Get the groups to which a user belongs Args: name (str): The user name to query sid (bool): True will return a list of SIDs, False will return a list of group names Returns: list: A list of group names or sids """ groups = [] if name.upper() == "SYSTEM": # 'win32net.NetUserGetLocalGroups' will fail if you pass in 'SYSTEM'. groups = ["SYSTEM"] else: try: groups = win32net.NetUserGetLocalGroups(None, name) except (win32net.error, pywintypes.error) as exc: # ERROR_ACCESS_DENIED, NERR_DCNotFound, RPC_S_SERVER_UNAVAILABLE if exc.winerror in (5, 1722, 2453, 1927, 1355): # Try without LG_INCLUDE_INDIRECT flag, because the user might # not have permissions for it or something is wrong with DC groups = win32net.NetUserGetLocalGroups(None, name, 0) else: # If this fails, try once more but instead with global groups. try: groups = win32net.NetUserGetGroups(None, name) except win32net.error as exc: if exc.winerror in (5, 1722, 2453, 1927, 1355): # Try without LG_INCLUDE_INDIRECT flag, because the user might # not have permissions for it or something is wrong with DC groups = win32net.NetUserGetLocalGroups(None, name, 0) except pywintypes.error: if exc.winerror in (5, 1722, 2453, 1927, 1355): # Try with LG_INCLUDE_INDIRECT flag, because the user might # not have permissions for it or something is wrong with DC groups = win32net.NetUserGetLocalGroups(None, name, 1) else: raise if not sid: return groups ret_groups = [] for group in groups: ret_groups.append(get_sid_from_name(group)) return ret_groups
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
def get_groups(self): if self.member_of: return self.member_of from wpc.group import group as Group # we have to import here to avoid circular import g1 = [] g2 = [] try: g1 = win32net.NetUserGetLocalGroups(wpc.conf.remote_server, self.get_name(), 0) except: pass try: g2 = win32net.NetUserGetGroups(wpc.conf.remote_server, self.get_name()) except: pass for g in g2: g1.append(g[0]) for group in g1: gsid, s, i = wpc.conf.cache.LookupAccountName( wpc.conf.remote_server, group) self.member_of.append(Group(gsid)) return self.member_of
def users(): result = [] users, _, _ = win32net.NetUserEnum(None, 3) current = win32api.GetUserName() UF_ACCOUNT_DISABLE = 2 UF_LOCKOUT = 16 for user in users: if user['flags'] & (UF_ACCOUNT_DISABLE | UF_LOCKOUT): continue result.append({ 'name': to_unicode(user['name']), 'groups': [ to_unicode(x) for x in win32net.NetUserGetLocalGroups( None, user['name']) ], 'admin': user['priv'] == 2, 'home': (to_unicode(user['logon_server']) + u'\\' + to_unicode(user['home_dir'])) if user['home_dir'] else u'default' }) return {'current': current, 'users': result}
def get_user_groups(name, sid=False): ''' Get the groups to which a user belongs Args: name (str): The user name to query sid (bool): True will return a list of SIDs, False will return a list of group names Returns: list: A list of group names or sids ''' if name == 'SYSTEM': # 'win32net.NetUserGetLocalGroups' will fail if you pass in 'SYSTEM'. groups = [name] else: groups = win32net.NetUserGetLocalGroups(None, name) if not sid: return groups ret_groups = set() for group in groups: ret_groups.add(get_sid_from_name(group)) return ret_groups
def get_max_status(self): mx = 1 for u in self.w.Win32_UserAccount(): tmp = len(win32net.NetUserGetLocalGroups (None, u.Name)) if tmp > mx: mx = tmp return mx
def check_user(machine_name, user_name): # Check if user is part of the administrator's group user_name = os.environ['UserDomain'] + '\\' + user_name group_membership = groups = win32net.NetUserGetLocalGroups(machine_name, user_name) if 'Administrators' in group_membership: return True else: return False
def Main(): cgiEnv = lib_common.CgiEnv(can_process_remote=True) try: # Exception if local machine. hostName = cgiEnv.m_entity_id_dict["Domain"] except KeyError: hostName = None if not hostName or lib_util.IsLocalAddress(hostName): serverBox = lib_common.gUriGen serverNode = lib_common.nodeMachine servName_or_None = None else: serverBox = lib_common.RemoteBox(hostName) serverNode = lib_common.gUriGen.HostnameUri(hostName) servName_or_None = hostName # hostname = "Titi" for example try: lib_win32.WNetAddConnect(hostName) except: lib_common.ErrorMessageHtml("Error WNetAddConnect %s:%s" % (hostName, str(sys.exc_info()))) userName = cgiEnv.m_entity_id_dict["Name"] DEBUG("hostName=%s userName=%s", hostName, userName) grph = cgiEnv.GetGraph() nodeUser = survol_Win32_UserAccount.MakeUri(userName, hostName) # TODO: Quid de NetUserGetGroups ?? # [(groupName, attribute), ...] = NetUserGetGroups(serverName, userName ) try: resuList = win32net.NetUserGetLocalGroups(servName_or_None, userName) except: lib_common.ErrorMessageHtml("Error:userName="******":servName_or_None=" + str(servName_or_None) + ":" + str(sys.exc_info())) for groupName in resuList: nodeGroup = survol_Win32_Group.MakeUri(groupName, hostName) grph.add((nodeUser, pc.property_group, nodeGroup)) if hostName: nodeGroupRemote = serverBox.UriMakeFromDict( "Win32_Group", { "Name": groupName, "Domain": hostName }) # TODO: Instead, both object must have the same universal alias grph.add((nodeGroup, pc.property_alias, nodeGroupRemote)) cgiEnv.OutCgiRdf()
def isUserAdmin(): groups = win32net.NetUserGetLocalGroups(os.environ["logonserver"], os.getlogin()) isadmin = False for group in groups: if group.lower().startswith("admin"): isadmin = True break return isadmin
def Main(): cgiEnv = lib_common.ScriptEnvironment(can_process_remote=True) try: # Exception if local machine. host_name = cgiEnv.m_entity_id_dict["Domain"] except KeyError: host_name = None if lib_util.is_local_address(host_name): server_box = lib_uris.gUriGen serv_name_or_none = None else: server_box = lib_common.RemoteBox(host_name) serv_name_or_none = host_name try: lib_win32.WNetAddConnect(host_name) except Exception as exc: lib_common.ErrorMessageHtml("Error WNetAddConnect %s:%s" % (host_name, str(exc))) user_name = cgiEnv.m_entity_id_dict["Name"] logging.debug("host_name=%s user_name=%s", host_name, user_name) grph = cgiEnv.GetGraph() node_user = survol_Win32_UserAccount.MakeUri(user_name, host_name) # TODO: And NetUserGetGroups ?? # [(group_name, attribute), ...] = NetUserGetGroups(serverName, user_name ) try: resu_list = win32net.NetUserGetLocalGroups(serv_name_or_none, user_name) except Exception as exc: lib_common.ErrorMessageHtml("Error:user_name=" + user_name + ":serv_name_or_none=" + str(serv_name_or_none) + ":" + str(exc)) for group_name in resu_list: node_group = survol_Win32_Group.MakeUri(group_name, host_name) grph.add((node_user, pc.property_group, node_group)) if host_name: node_group_remote = server_box.node_from_dict( "Win32_Group", { "Name": group_name, "Domain": host_name }) # TODO: Instead, both object must have the same universal alias grph.add((node_group, pc.property_alias, node_group_remote)) cgiEnv.OutCgiRdf()
def Groups(user_name=Name(), server=None): """ Retrieves direct and indirect group name the username is a member of for a specific computer/server. If no parameters are passed it will default to the current user and the local computer. :type user_name: str :type server: str :rtype: list """ return win32net.NetUserGetLocalGroups(server, user_name)
def get_groups_names(username): """ Works on windows and *nix :param username: A string representing a username :return: A set or list (collection) of group names that the user has """ if not pwd or not grp: return win32net.NetUserGetLocalGroups(platform.uname()[1], username) groups = set(g.gr_name for g in grp.getgrall() if username in g.gr_mem) gid = pwd.getpwnam(username).pw_gid groups.add(grp.getgrgid(gid).gr_name) return groups
def _set_standard_users(self, users): common.info("Setting standard users...") for user in users: if "Linux" in plugin.get_os(): # set only group to be the user's primary group common.run("usermod -G {0} {0}".format(user)) common.run("usermod -aG users {}".format(user)) common.info("Removed all groups from user {}".format(user)) elif "Windows" in plugin.get_os(): groups = win32net.NetUserGetLocalGroups(None, user) for group in groups: if group != "Users": os.system( "net localgroup \"{}\" \"{}\" /delete".format( group, user))
def _set_admin_users(self, users): common.info("Setting admin users...") for user in users: if "Linux" in plugin.get_os(): # list of groups we want to add the user to admin_roles = ["sudo", "adm"] # add the admin roles common.run("usermod -aG {0} {1}".format( ",".join(admin_roles), user)) elif "Windows" in plugin.get_os(): groups = win32net.NetUserGetLocalGroups(None, user) if "Administrators" not in groups: os.system( "net localgroup Administrators \"{}\" /add".format( user))
def get_user_groups(name, sid=False): ''' Get the groups to which a user belongs Args: name (str): The user name to query sid (bool): True will return a list of SIDs, False will return a list of group names Returns: list: A list of group names or sids ''' groups = [] if name.upper() == 'SYSTEM': # 'win32net.NetUserGetLocalGroups' will fail if you pass in 'SYSTEM'. groups = ['SYSTEM'] else: try: groups = win32net.NetUserGetLocalGroups(None, name) except win32net.error as exc: # ERROR_ACCESS_DENIED, NERR_DCNotFound, RPC_S_SERVER_UNAVAILABLE if exc.winerror in (5, 1722, 2453): # Try without LG_INCLUDE_INDIRECT flag, because the user might # not have permissions for it or something is wrong with DC groups = win32net.NetUserGetLocalGroups(None, name, 0) else: raise if not sid: return groups ret_groups = [] for group in groups: ret_groups.append(get_sid_from_name(group)) return ret_groups
def is_user_in_group(user_name, group_name): ret = False try: server_name = None # for local machine groups = win32net.NetUserGetLocalGroups(server_name, user_name, 0) for g in groups: if g.lower() == group_name.lower(): # Found group! ret = True break # Break out of loop except Exception as ex: p("}}rnERROR - Unknown Error trying to get groups for user!]n}}xx" + \ str(ex)) return None return ret
def listLocalUsers(): try: users = win32net.NetUserEnum('localhost', 0) except: print_fail('[!] Error with NetUserEnum API call, cannot list users') #print win32api.GetLastError() return None usernames = [] print 'Local User Accounts (with Local Groups)' print '---------------------------------------' for user in users[0]: usernames.append(user['name']) groups = win32net.NetUserGetLocalGroups(None, user['name'], 0) if 'Administrators' in groups or 'Administrateurs' in groups: print_yellow(' %s [%s]' % (user['name'], '-'.join(groups))) else: print ' %s [%s]' % (user['name'], '-'.join(groups)) print return usernames
def get_info(self, user): d = { 'status': str(win32net.NetUserGetLocalGroups(None, user.Name)), 'name': user.Name, 'fullname': user.FullName, 'caption': user.Caption, 'description': user.Description, 'disabled': user.Disabled, 'domain': user.Domain, 'installdate': user.InstallDate, 'localaccount': user.LocalAccount, 'lockout': user.Lockout, 'passwordchangeable': user.PasswordChangeable, 'passwordexpires': user.PasswordExpires, 'passwordrequired': user.PasswordRequired, } return d
def info(name): ''' Return user information CLI Example: .. code-block:: bash salt '*' user.info root ''' ret = {} items = {} try: items = win32net.NetUserGetInfo(None, name, 4) except win32net.error: pass if items: groups = [] try: groups = win32net.NetUserGetLocalGroups(None, name) except win32net.error: pass ret['fullname'] = items['full_name'] ret['name'] = items['name'] ret['uid'] = win32security.ConvertSidToStringSid(items['user_sid']) ret['passwd'] = items['password'] ret['comment'] = items['comment'] ret['active'] = ( not bool(items['flags'] & win32netcon.UF_ACCOUNTDISABLE)) ret['logonscript'] = items['script_path'] ret['profile'] = items['profile'] if not ret['profile']: ret['profile'] = _get_userprofile_from_registry(name, ret['uid']) ret['home'] = items['home_dir'] if not ret['home']: ret['home'] = ret['profile'] ret['groups'] = groups ret['gid'] = '' return ret
def users(): result = [] users, _, _ = win32net.NetUserEnum(None, 1) current = win32api.GetUserName() UF_ACCOUNT_DISABLE = 2 UF_LOCKOUT = 16 for user in users: if user['flags'] & (UF_ACCOUNT_DISABLE | UF_LOCKOUT): continue result.append({ 'name': user['name'], 'groups': win32net.NetUserGetLocalGroups(None, user['name']), 'admin': user['priv'] == 2 }) return {'current': current, 'users': result}
def users_info(self): result = [] users, _, _ = win32net.NetUserEnum(None, 3) current = GetUserName() UF_ACCOUNT_DISABLE = 2 UF_LOCKOUT = 16 PASSWD_NOTREQD = 32 for user in users: # Remove all uninteresting accounts if user['flags'] & (UF_ACCOUNT_DISABLE | UF_LOCKOUT) or user['name'] == current: continue # Check if password is required passwd_req = True if user['flags'] & PASSWD_NOTREQD: passwd_req = False # print win32net.NetUserGetInfo(None, user['name'], 1) result.append({ 'name': to_unicode(user['name']), 'groups': [ to_unicode(x) for x in win32net.NetUserGetLocalGroups( None, user['name']) ], 'admin': user['priv'] == 2, 'password_required': passwd_req, 'home': (to_unicode(user['logon_server']) + u'\\' + to_unicode(user['home_dir'])) if user['home_dir'] else u'default' }) return result
def is_in_admin_group(user_name=None): # Get the list of groups for this user - if not in admin, return false ret = False try: server_name = None # None for local machine if user_name is None: user_name = win32api.GetUserName() if user_name == "SYSTEM": # SYSTEM user counts! return True # p("}}ynChecking Admin Membership for: " + user_name) groups = win32net.NetUserGetLocalGroups(server_name, user_name, 0) for g in groups: if g.lower() == "administrators": ret = True except Exception as ex: p("}}rnERROR - Unknown Error! }}xx\n" + str(ex)) ret = False return ret
def info(name): """ Return user information Args: name (str): Username for which to display information Returns: dict: A dictionary containing user information - fullname - username - SID - passwd (will always return None) - comment (same as description, left here for backwards compatibility) - description - active - logonscript - profile - home - homedrive - groups - password_changed - successful_logon_attempts - failed_logon_attempts - last_logon - account_disabled - account_locked - password_never_expires - disallow_change_password - gid CLI Example: .. code-block:: bash salt '*' user.info jsnuffy """ if six.PY2: name = _to_unicode(name) ret = {} items = {} try: items = win32net.NetUserGetInfo(None, name, 4) except win32net.error: pass if items: groups = [] try: groups = win32net.NetUserGetLocalGroups(None, name) except win32net.error: pass ret["fullname"] = items["full_name"] ret["name"] = items["name"] ret["uid"] = win32security.ConvertSidToStringSid(items["user_sid"]) ret["passwd"] = items["password"] ret["comment"] = items["comment"] ret["description"] = items["comment"] ret["active"] = not bool(items["flags"] & win32netcon.UF_ACCOUNTDISABLE) ret["logonscript"] = items["script_path"] ret["profile"] = items["profile"] ret["failed_logon_attempts"] = items["bad_pw_count"] ret["successful_logon_attempts"] = items["num_logons"] secs = time.mktime(datetime.now().timetuple()) - items["password_age"] ret["password_changed"] = datetime.fromtimestamp(secs).strftime( "%Y-%m-%d %H:%M:%S") if items["last_logon"] == 0: ret["last_logon"] = "Never" else: ret["last_logon"] = datetime.fromtimestamp( items["last_logon"]).strftime("%Y-%m-%d %H:%M:%S") ret["expiration_date"] = datetime.fromtimestamp( items["acct_expires"]).strftime("%Y-%m-%d %H:%M:%S") ret["expired"] = items["password_expired"] == 1 if not ret["profile"]: ret["profile"] = _get_userprofile_from_registry(name, ret["uid"]) ret["home"] = items["home_dir"] ret["homedrive"] = items["home_dir_drive"] if not ret["home"]: ret["home"] = ret["profile"] ret["groups"] = groups if items["flags"] & win32netcon.UF_DONT_EXPIRE_PASSWD == 0: ret["password_never_expires"] = False else: ret["password_never_expires"] = True if items["flags"] & win32netcon.UF_ACCOUNTDISABLE == 0: ret["account_disabled"] = False else: ret["account_disabled"] = True if items["flags"] & win32netcon.UF_LOCKOUT == 0: ret["account_locked"] = False else: ret["account_locked"] = True if items["flags"] & win32netcon.UF_PASSWD_CANT_CHANGE == 0: ret["disallow_change_password"] = False else: ret["disallow_change_password"] = True ret["gid"] = "" return ret else: return {}
def info(name): ''' Return user information :param name: str Username for which to display information :returns: dict A dictionary containing user information - fullname - username - uid - passwd (will always return None) - comment (same as description, left here for backwards compatibility) - description - active - logonscript - profile - home - homedrive - groups - gid CLI Example: .. code-block:: bash salt '*' user.info root ''' ret = {} items = {} try: items = win32net.NetUserGetInfo(None, name, 4) except win32net.error: pass if items: groups = [] try: groups = win32net.NetUserGetLocalGroups(None, name) except win32net.error: pass ret['fullname'] = items['full_name'] ret['name'] = items['name'] ret['uid'] = win32security.ConvertSidToStringSid(items['user_sid']) ret['passwd'] = items['password'] ret['comment'] = items['comment'] ret['description'] = items['comment'] ret['active'] = ( not bool(items['flags'] & win32netcon.UF_ACCOUNTDISABLE)) ret['logonscript'] = items['script_path'] ret['profile'] = items['profile'] if not ret['profile']: ret['profile'] = _get_userprofile_from_registry(name, ret['uid']) ret['home'] = items['home_dir'] ret['homedrive'] = items['home_dir_drive'] if not ret['home']: ret['home'] = ret['profile'] ret['groups'] = groups ret['gid'] = '' return ret
def groups(): group = win32net.NetUserGetLocalGroups(None, os.getlogin()) return group
def info(name): ''' Return user information Args: name (str): Username for which to display information Returns: dict: A dictionary containing user information - fullname - username - SID - passwd (will always return None) - comment (same as description, left here for backwards compatibility) - description - active - logonscript - profile - home - homedrive - groups - password_changed - successful_logon_attempts - failed_logon_attempts - last_logon - account_disabled - account_locked - password_never_expires - disallow_change_password - gid CLI Example: .. code-block:: bash salt '*' user.info jsnuffy ''' if six.PY2: name = _to_unicode(name) ret = {} items = {} try: items = win32net.NetUserGetInfo(None, name, 4) except win32net.error: pass if items: groups = [] try: groups = win32net.NetUserGetLocalGroups(None, name) except win32net.error: pass ret['fullname'] = items['full_name'] ret['name'] = items['name'] ret['uid'] = win32security.ConvertSidToStringSid(items['user_sid']) ret['passwd'] = items['password'] ret['comment'] = items['comment'] ret['description'] = items['comment'] ret['active'] = ( not bool(items['flags'] & win32netcon.UF_ACCOUNTDISABLE)) ret['logonscript'] = items['script_path'] ret['profile'] = items['profile'] ret['failed_logon_attempts'] = items['bad_pw_count'] ret['successful_logon_attempts'] = items['num_logons'] secs = time.mktime(datetime.now().timetuple()) - items['password_age'] ret['password_changed'] = datetime.fromtimestamp(secs). \ strftime('%Y-%m-%d %H:%M:%S') if items['last_logon'] == 0: ret['last_logon'] = 'Never' else: ret['last_logon'] = datetime.fromtimestamp(items['last_logon']).\ strftime('%Y-%m-%d %H:%M:%S') ret['expiration_date'] = datetime.fromtimestamp(items['acct_expires']).\ strftime('%Y-%m-%d %H:%M:%S') ret['expired'] = items['password_expired'] == 1 if not ret['profile']: ret['profile'] = _get_userprofile_from_registry(name, ret['uid']) ret['home'] = items['home_dir'] ret['homedrive'] = items['home_dir_drive'] if not ret['home']: ret['home'] = ret['profile'] ret['groups'] = groups if items['flags'] & win32netcon.UF_DONT_EXPIRE_PASSWD == 0: ret['password_never_expires'] = False else: ret['password_never_expires'] = True if items['flags'] & win32netcon.UF_ACCOUNTDISABLE == 0: ret['account_disabled'] = False else: ret['account_disabled'] = True if items['flags'] & win32netcon.UF_LOCKOUT == 0: ret['account_locked'] = False else: ret['account_locked'] = True if items['flags'] & win32netcon.UF_PASSWD_CANT_CHANGE == 0: ret['disallow_change_password'] = False else: ret['disallow_change_password'] = True ret['gid'] = '' return ret else: return {}
from tkinter import * import platform import os import socket import getpass import sys import subprocess import win32net import win32netcon import time import wmi w = wmi.WMI() for u in w.Win32_UserAccount(): # Net print(u.Name + ' -> ' + str(win32net.NetUserGetLocalGroups(None, u.Name))) width = '500' height = '500' shift_x = '+100' shift_y = '+50' root = Tk() # create a main window root.title('Test') root.geometry(width + 'x' + height + shift_x + shift_y) # geometry of window ############################################################################### myhost = socket.gethostname() # get hostname Label(root, text='Hostname:').place(x=10, y=10)