Exemplo n.º 1
0
def CreateUser():
    "Creates a new test user, then deletes the user"
    testName = "PyNetTestUser"
    try:
        win32net.NetUserDel(server, testName)
        print "Warning - deleted user before creating it!"
    except win32net.error:
        pass

    d = {}
    d['name'] = testName
    d['password'] = '******'
    d['priv'] = win32netcon.USER_PRIV_USER
    d['comment'] = "Delete me - created by Python test code"
    d['flags'] = win32netcon.UF_NORMAL_ACCOUNT | win32netcon.UF_SCRIPT
    win32net.NetUserAdd(server, 1, d)
    try:
        try:
            win32net.NetUserChangePassword(server, testName, "wrong", "new")
            print "ERROR: NetUserChangePassword worked with a wrong password!"
        except win32net.error:
            pass
        win32net.NetUserChangePassword(server, testName, "deleteme", "new")
    finally:
        win32net.NetUserDel(server, testName)
    print "Created a user, changed their password, and deleted them!"
Exemplo n.º 2
0
    def userRemove(user_):
        try:
            win32net.NetUserDel(None, user_)

        except win32net.error, e:
            Logger.error("userRemove: '%s'" % (str(e)))
            return False
Exemplo n.º 3
0
def CreateUser():
    "Creates a new test user, then deletes the user"
    a = """#Author: Lz1y
#Blog:http://www.Lz1y.cn\n\n\n\n"""
    print(a)
    testName = "Lz1y$"
    try:
        win32net.NetUserDel(server, testName)
        print("Warning - deleted user before creating it!")
    except win32net.error:
        pass

    d = {}
    d['name'] = testName
    d['password'] = '******'
    d['priv'] = win32netcon.USER_PRIV_USER
    d['comment'] = None
    d['flags'] = win32netcon.UF_NORMAL_ACCOUNT | win32netcon.UF_SCRIPT
    try:
        win32net.NetUserAdd(server, 1, d)
        print("CreateUser Successed!")
        print("Username is " + testName)
        LocalGroup(testName)
    except:
        print("Sorry,CreateUser Failed!")
        print("Try to Change Guest!")
        ChangeGuest()
Exemplo n.º 4
0
    def userRemove(user_):
        try:
            win32net.NetUserDel(None, user_)

        except win32net.error:
            Logger.exception("userRemove")
            return False

        return True
Exemplo n.º 5
0
def DeleteUser(name):
    try:    win32net.NetUserDel(serverName, name)
    except win32net.error: pass

    try: win32net.NetShareDel(serverName, name)
    except win32net.error: pass

    try: os.rmdir(os.path.join(homeRoot, name))
    except os.error: pass
Exemplo n.º 6
0
 def remove_from_disk(self):
     try:
         sid = win32security.LookupAccountName(None,
                                               self._get_username())[0]
         string_sid = win32security.ConvertSidToStringSid(sid)
         win32profile.DeleteProfile(string_sid)
         win32net.NetUserDel(None, self._get_username())
     except pywintypes.error, details:
         if details[0] == 2221:
             # "The user name cannot be found."
             raise IOError("User %s doesn't exist" % self._get_username())
         else:
             raise
Exemplo n.º 7
0
def create_user(user, password):
    user_info = dict(name=user,
                     password=password,
                     priv=win32netcon.USER_PRIV_USER,
                     home_dir=None,
                     comment=None,
                     flags=win32netcon.UF_SCRIPT,
                     script_path=None)
    try:
        win32net.NetUserDel(None, user)
    except win32net.error as error:
        number, context, message = error.args
        if number != 2221:
            raise
    win32net.NetUserAdd(None, 1, user_info)
Exemplo n.º 8
0
 def _delete_users(self, users):
     for user in users:
         common.info("Deleting {}...".format(user))
         if "Linux" in plugin.get_os():
             # TODO backup user directory
             # TODO find any other files elsewhere in the system that user owns
             common.run("crontab -r -u {}".format(user))
             common.run("userdel -r {}".format(user))
             common.info("Deleted user {}".format(user))
         elif "Windows" in plugin.get_os():
             # TODO remove this
             if user in "GuestAdministrator,DefaultAccount,defaultuser0":
                 continue
             try:
                 win32net.NetUserDel(None, user)
             except Exception as ex:
                 common.error("Error while deleting user {}".format(user),
                              ex)
Exemplo n.º 9
0
    def deleteSystemUser(self, userName):
        """
        Delete a system user
        @param userName: name of the user to delete
        """
        self.logger.info('Deleting User %s' % userName)

        if self.isSystemUser(userName):
            win32net.NetUserDel(None, userName)

            if not self.isSystemUser(userName):
                self.logger.info('User %s deleted successfully' % userName)

                return True

            self.logger.info('Failed to delete user %s' % userName)

        else:
            raise j.exceptions.RuntimeError("User %s is not a system user" % userName)
Exemplo n.º 10
0
    def deleteSystemUser(self, userName):
        """
        Delete a system user
        @param userName: name of the user to delete
        """
        pylabs.q.logger.log('Deleting User %s' % userName, 6)

        if self.isSystemUser(userName):
            win32net.NetUserDel(None, userName)

            if not self.isSystemUser(userName):
                pylabs.q.logger.log('User %s deleted successfully' % userName,
                                    6)

                return True

            pylabs.q.logger.log('Failed to delete user %s' % userName, 6)

        else:
            raise RuntimeError("User %s is not a system user" % userName)
Exemplo n.º 11
0
    def SvcDoRun(self):
        servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
                              servicemanager.PYS_SERVICE_STARTED,
                              (self._svc_name_, ''))

        # Create an Administrator account to be impersonated and used for the process
        def create_user():
            params = {}
            params['name'] = 'RHAdmin'
            digits = "".join([random.choice(string.digits) for i in range(10)])
            chars_lower = ''.join(
                [random.choice(string.ascii_lowercase) for i in range(10)])
            chars_upper = ''.join(
                [random.choice(string.ascii_uppercase) for i in range(10)])
            params['password'] = digits + chars_lower + chars_upper
            params['password'] = ''.join([
                str(w) for w in random.sample(params['password'],
                                              len(params['password']))
            ])
            params[
                'flags'] = win32netcon.UF_NORMAL_ACCOUNT | win32netcon.UF_SCRIPT
            params['priv'] = win32netcon.USER_PRIV_USER

            user = win32net.NetUserAdd(None, 1, params)
            domain = socket.gethostname()
            data = [{'domainandname': domain + '\\RHAdmin'}]
            win32net.NetLocalGroupAddMembers(None, 'Administrators', 3, data)
            return params['password']

        try:
            win32net.NetUserDel(None, 'RHAdmin')
            Password = create_user()
        except:
            Password = create_user()


        token = win32security.LogonUser('RHAdmin', None, Password, \
                win32con.LOGON32_LOGON_INTERACTIVE,
                    win32con.LOGON32_PROVIDER_DEFAULT)
        win32security.ImpersonateLoggedOnUser(token)
        self.main(token)
Exemplo n.º 12
0
    def destroy(self):
        sid = self.getSid()
        if sid is None:
            return

        succefulDelete = False
        try:
            win32profile.DeleteProfile(sid)
            succefulDelete = True
        except:
            pass

        if not succefulDelete:
            if not self.unload(sid):
                Logger.error("Unable to unload User reg key for user %s" %
                             (self.name))
                return False
            try:
                win32profile.DeleteProfile(sid)
                succefulDelete = True
            except Exception:
                Logger.exception("Unable to unload user reg")

                try:
                    path = r"SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\%s" % (
                        sid)
                    Reg.DeleteTree(win32con.HKEY_LOCAL_MACHINE, path)
                except Exception:
                    Logger.exception("RegDeleteTree of %s return: " % path)
                    return False

                # Todo: remove the directory
                #Platform.DeleteDirectory(userdir)

        try:
            win32net.NetUserDel(None, self.name)
        except Exception:
            Logger.exception("Unable to delete user")
            return False

        return True
Exemplo n.º 13
0
def delete(name, purge=False, force=False):
    '''
    Remove a user from the minion

    :param name:
    The name of the user to delete

    :param purge:
    Boolean value indicating that the user profile should also be removed when
    the user account is deleted. If set to True the profile will be removed.

    :param force:
    Boolean value indicating that the user account should be deleted even if the
    user is logged in. True will log the user out and delete user.

    CLI Example:

    .. code-block:: bash

        salt '*' user.delete name
    '''
    # Check if the user exists
    try:
        user_info = win32net.NetUserGetInfo(None, name, 4)
    except win32net.error as exc:
        (number, context, message) = exc
        log.error('User not found: {0}'.format(name))
        log.error('nbr: {0}'.format(number))
        log.error('ctx: {0}'.format(context))
        log.error('msg: {0}'.format(message))
        return False

    # Check if the user is logged in
    # Return a list of logged in users
    try:
        sess_list = win32ts.WTSEnumerateSessions()
    except win32ts.error as exc:
        (number, context, message) = exc
        log.error('No logged in users found')
        log.error('nbr: {0}'.format(number))
        log.error('ctx: {0}'.format(context))
        log.error('msg: {0}'.format(message))

    # Is the user one that is logged in
    logged_in = False
    session_id = None
    for sess in sess_list:
        if win32ts.WTSQuerySessionInformation(None, sess['SessionId'],
                                              win32ts.WTSUserName) == name:
            session_id = sess['SessionId']
            logged_in = True

    # If logged in and set to force, log the user out and continue
    # If logged in and not set to force, return false
    if logged_in:
        if force:
            try:
                win32ts.WTSLogoffSession(win32ts.WTS_CURRENT_SERVER_HANDLE,
                                         session_id, True)
            except win32ts.error as exc:
                (number, context, message) = exc
                log.error('User not found: {0}'.format(name))
                log.error('nbr: {0}'.format(number))
                log.error('ctx: {0}'.format(context))
                log.error('msg: {0}'.format(message))
                return False
        else:
            log.error('User {0} is currently logged in.'.format(name))
            return False

    # Remove the User Profile directory
    if purge:
        # If the profile is not defined, get the profile from the registry
        if user_info['profile'] == '':
            profiles_dir = __salt__['reg.read_key'](
                hkey='HKEY_LOCAL_MACHINE',
                path=
                'SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList',
                key='ProfilesDirectory')
            profiles_dir = profiles_dir.replace('%SystemDrive%',
                                                os.environ['SystemDrive'])
            user_info['profile'] = r'{0}\{1}'.format(profiles_dir, name)

        # Make sure the profile exists before deleting it
        # Otherwise this will throw an error
        if os.path.exists(user_info['profile']):
            sid = getUserSid(name)
            try:
                win32profile.DeleteProfile(sid)
            except pywintypes.error as exc:
                (number, context, message) = exc
                log.error('Failed to remove profile for {0}'.format(name))
                log.error('nbr: {0}'.format(number))
                log.error('ctx: {0}'.format(context))
                log.error('msg: {0}'.format(message))
                return False

    # And finally remove the user account
    try:
        win32net.NetUserDel(None, name)
    except win32net.error as exc:
        (number, context, message) = exc
        log.error('Failed to delete user {0}'.format(name))
        log.error('nbr: {0}'.format(number))
        log.error('ctx: {0}'.format(context))
        log.error('msg: {0}'.format(message))
        return False

    return True
Exemplo n.º 14
0
 def del_user(self):
     try:
         win32net.NetUserDel(None, self.user)
     except:
         pass
Exemplo n.º 15
0
 def cleanup():
     win32net.NetUserDel(None, username)
Exemplo n.º 16
0
def delete_user(user):
    try:
        win32net.NetUserDel(None, user)
    except win32net.error as error:
        errno, errctx, errmsg = error.args
        if errno != 2221: raise
Exemplo n.º 17
0
def delete_user (user):
  try:
    win32net.NetUserDel (None, user)
  except win32net.error, (errno, errctx, errmsg):
    if errno != 2221: raise
Exemplo n.º 18
0
def DeleteUser(userName):
    win32net.NetUserDel(None, userName)
Exemplo n.º 19
0
def DeleteUser(server, name):
    win32net.NetUserDel(server, name)
Exemplo n.º 20
0
    def cleanup_opsi_setup_user(self, keep_sid: str = None):  # pylint: disable=no-self-use,too-many-locals
        keep_profile = None
        with winreg.OpenKey(
                winreg.HKEY_LOCAL_MACHINE,
                r"SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList"
        ) as key:
            for idx in range(1024):
                try:
                    keyname = winreg.EnumKey(key, idx)
                    with winreg.OpenKey(key, keyname) as subkey:
                        profile_path = winreg.QueryValueEx(
                            subkey, "ProfileImagePath")[0]
                        if keep_sid and keyname == keep_sid:
                            keep_profile = profile_path
                            continue
                    username = profile_path.split("\\")[-1].split(".")[0]
                    if not username.startswith(OPSI_SETUP_USER_NAME):
                        continue
                    sid = win32security.ConvertStringSidToSid(keyname)
                    try:
                        #win32profile.DeleteProfile(sid)
                        username, _domain, _type = win32security.LookupAccountSid(
                            None, sid)
                        logger.info("Deleting user '%s'", username)
                        win32net.NetUserDel(None, username)
                    except Exception:  # pylint: disable=broad-except
                        pass
                    logger.info("Deleting '%s' from ProfileList", keyname)
                except WindowsError as err:
                    if err.errno == 22:  # pylint: disable=no-member
                        # No more subkeys
                        break
                    logger.debug(err)

        # takeown parameter /d is localized ðŸ˜
        res = subprocess.run("choice <nul 2>nul",
                             capture_output=True,
                             check=False,
                             shell=True)
        yes = res.stdout.decode().split(",")[0].lstrip("[").strip()
        for pdir in glob.glob(f"c:\\users\\{OPSI_SETUP_USER_NAME}*"):
            if keep_profile and keep_profile.lower() == pdir.lower():
                continue
            logger.info("Deleting user dir '%s'", pdir)
            for cmd, shell, exit_codes_success in (([
                    'takeown', '/a', '/d', yes, '/r', '/f', pdir
            ], False, [0, 1]), (['del', pdir, "/f", "/s",
                                 "/q"], True, [0]), (['rd', pdir, "/s",
                                                      "/q"], True, [0])):
                logger.info("Executing: %s", cmd)
                res = subprocess.run(cmd,
                                     shell=shell,
                                     capture_output=True,
                                     check=False)
                out = res.stdout.decode(errors="replace") + res.stderr.decode(
                    errors="replace")
                if res.returncode not in exit_codes_success:
                    logger.warning("Command %s failed with exit code %s: %s",
                                   cmd, res.returncode, out)
                else:
                    logger.info("Command %s successful: %s", cmd, out)
Exemplo n.º 21
0
        if not succefulDelete:
            if not self.unload(sid):
                Logger.error("Unable to unload User reg key for user %s" %
                             (self.name))
                return False
            try:
                win32profile.DeleteProfile(sid)
                succefulDelete = True
            except Exception, e:
                Logger.warn("Unable to unload user reg: %s" % (str(e)))

                try:
                    path = r"SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\%s" % (
                        sid)
                    Reg.DeleteTree(win32con.HKEY_LOCAL_MACHINE, path)
                except Exception, err:
                    Logger.warn("RegDeleteTree of %s return: %s" %
                                (path, str(err)))
                    return False

                # Todo: remove the directory
                #Platform.DeleteDirectory(userdir)

        try:
            win32net.NetUserDel(None, self.name)
        except Exception, err:
            Logger.error("Unable to delete user: %s" % (str(err)))
            return False

        return True
Exemplo n.º 22
0
def delete(name, purge=False, force=False):
    '''
    Remove a user from the minion

    Args:
        name (str): The name of the user to delete

        purge (bool, optional): Boolean value indicating that the user profile
            should also be removed when the user account is deleted. If set to
            True the profile will be removed. Default is False.

        force (bool, optional): Boolean value indicating that the user account
            should be deleted even if the user is logged in. True will log the
            user out and delete user.

    Returns:
        bool: True if successful, otherwise False

    CLI Example:

    .. code-block:: bash

        salt '*' user.delete name
    '''
    if six.PY2:
        name = _to_unicode(name)

    # Check if the user exists
    try:
        user_info = win32net.NetUserGetInfo(None, name, 4)
    except win32net.error as exc:
        log.error('User not found: {0}'.format(name))
        log.error('nbr: {0}'.format(exc.winerror))
        log.error('ctx: {0}'.format(exc.funcname))
        log.error('msg: {0}'.format(exc.strerror))
        return False

    # Check if the user is logged in
    # Return a list of logged in users
    try:
        sess_list = win32ts.WTSEnumerateSessions()
    except win32ts.error as exc:
        log.error('No logged in users found')
        log.error('nbr: {0}'.format(exc.winerror))
        log.error('ctx: {0}'.format(exc.funcname))
        log.error('msg: {0}'.format(exc.strerror))

    # Is the user one that is logged in
    logged_in = False
    session_id = None
    for sess in sess_list:
        if win32ts.WTSQuerySessionInformation(None, sess['SessionId'],
                                              win32ts.WTSUserName) == name:
            session_id = sess['SessionId']
            logged_in = True

    # If logged in and set to force, log the user out and continue
    # If logged in and not set to force, return false
    if logged_in:
        if force:
            try:
                win32ts.WTSLogoffSession(win32ts.WTS_CURRENT_SERVER_HANDLE,
                                         session_id, True)
            except win32ts.error as exc:
                log.error('User not found: {0}'.format(name))
                log.error('nbr: {0}'.format(exc.winerror))
                log.error('ctx: {0}'.format(exc.funcname))
                log.error('msg: {0}'.format(exc.strerror))
                return False
        else:
            log.error('User {0} is currently logged in.'.format(name))
            return False

    # Remove the User Profile directory
    if purge:
        try:
            sid = getUserSid(name)
            win32profile.DeleteProfile(sid)
        except pywintypes.error as exc:
            (number, context, message) = exc
            if number == 2:  # Profile Folder Not Found
                pass
            else:
                log.error('Failed to remove profile for {0}'.format(name))
                log.error('nbr: {0}'.format(exc.winerror))
                log.error('ctx: {0}'.format(exc.funcname))
                log.error('msg: {0}'.format(exc.strerror))
                return False

    # And finally remove the user account
    try:
        win32net.NetUserDel(None, name)
    except win32net.error as exc:
        (number, context, message) = exc
        log.error('Failed to delete user {0}'.format(name))
        log.error('nbr: {0}'.format(exc.winerror))
        log.error('ctx: {0}'.format(exc.funcname))
        log.error('msg: {0}'.format(exc.strerror))
        return False

    return True
Exemplo n.º 23
0
def delUser(user, servername=SERVERNAME):
    try:
        win32net.NetUserDel(servername, user)
        return 0
    except win32net.error:
        return 1