Esempio n. 1
0
def update(name,
           password=None,
           fullname=None,
           description=None,
           home=None,
           homedrive=None,
           logonscript=None,
           profile=None,
           expiration_date=None,
           expired=None,
           account_disabled=None,
           unlock_account=None,
           password_never_expires=None,
           disallow_change_password=None):
    # pylint: disable=anomalous-backslash-in-string
    '''
    Updates settings for the windows user. Name is the only required parameter.
    Settings will only be changed if the parameter is passed a value.

    .. versionadded:: 2015.8.0

    Args:
        name (str): The user name to update.

        password (str, optional): New user password in plain text.

        fullname (str, optional): The user's full name.

        description (str, optional): A brief description of the user account.

        home (str, optional): The path to the user's home directory.

        homedrive (str, optional): The drive letter to assign to the home
            directory. Must be the Drive Letter followed by a colon. ie: U:

        logonscript (str, optional): The path to the logon script.

        profile (str, optional): The path to the user's profile directory.

        expiration_date (date, optional): The date and time when the account
            expires. Can be a valid date/time string. To set to never expire
            pass the string 'Never'.

        expired (bool, optional): Pass `True` to expire the account. The user
            will be prompted to change their password at the next logon. Pass
            `False` to mark the account as 'not expired'. You can't use this to
            negate the expiration if the expiration was caused by the account
            expiring. You'll have to change the `expiration_date` as well.

        account_disabled (bool, optional): True disables the account. False
            enables the account.

        unlock_account (bool, optional): True unlocks a locked user account.
            False is ignored.

        password_never_expires (bool, optional): True sets the password to never
            expire. False allows the password to expire.

        disallow_change_password (bool, optional): True blocks the user from
            changing the password. False allows the user to change the password.

    Returns:
        bool: True if successful. False is unsuccessful.

    CLI Example:

    .. code-block:: bash

        salt '*' user.update bob password=secret profile=C:\\Users\\Bob
                 home=\\server\homeshare\bob homedrive=U:
    '''
    # pylint: enable=anomalous-backslash-in-string
    if six.PY2:
        name = _to_unicode(name)
        password = _to_unicode(password)
        fullname = _to_unicode(fullname)
        description = _to_unicode(description)
        home = _to_unicode(home)
        homedrive = _to_unicode(homedrive)
        logonscript = _to_unicode(logonscript)
        profile = _to_unicode(profile)

    # Make sure the user exists
    # Return an object containing current settings for the user
    try:
        user_info = win32net.NetUserGetInfo(None, name, 4)
    except win32net.error as exc:
        log.error('Failed to update user %s', name)
        log.error('nbr: %s', exc.winerror)
        log.error('ctx: %s', exc.funcname)
        log.error('msg: %s', exc.strerror)
        return False

    # Check parameters to update
    # Update the user object with new settings
    if password:
        user_info['password'] = password
    if home:
        user_info['home_dir'] = home
    if homedrive:
        user_info['home_dir_drive'] = homedrive
    if description:
        user_info['comment'] = description
    if logonscript:
        user_info['script_path'] = logonscript
    if fullname:
        user_info['full_name'] = fullname
    if profile:
        user_info['profile'] = profile
    if expiration_date:
        if expiration_date == 'Never':
            user_info['acct_expires'] = win32netcon.TIMEQ_FOREVER
        else:
            try:
                dt_obj = salt.utils.dateutils.date_cast(expiration_date)
            except (ValueError, RuntimeError):
                return 'Invalid Date/Time Format: {0}'.format(expiration_date)
            user_info['acct_expires'] = time.mktime(dt_obj.timetuple())
    if expired is not None:
        if expired:
            user_info['password_expired'] = 1
        else:
            user_info['password_expired'] = 0
    if account_disabled is not None:
        if account_disabled:
            user_info['flags'] |= win32netcon.UF_ACCOUNTDISABLE
        else:
            user_info['flags'] &= ~win32netcon.UF_ACCOUNTDISABLE
    if unlock_account is not None:
        if unlock_account:
            user_info['flags'] &= ~win32netcon.UF_LOCKOUT
    if password_never_expires is not None:
        if password_never_expires:
            user_info['flags'] |= win32netcon.UF_DONT_EXPIRE_PASSWD
        else:
            user_info['flags'] &= ~win32netcon.UF_DONT_EXPIRE_PASSWD
    if disallow_change_password is not None:
        if disallow_change_password:
            user_info['flags'] |= win32netcon.UF_PASSWD_CANT_CHANGE
        else:
            user_info['flags'] &= ~win32netcon.UF_PASSWD_CANT_CHANGE

    # Apply new settings
    try:
        win32net.NetUserSetInfo(None, name, 4, user_info)
    except win32net.error as exc:
        log.error('Failed to update user %s', name)
        log.error('nbr: %s', exc.winerror)
        log.error('ctx: %s', exc.funcname)
        log.error('msg: %s', exc.strerror)
        return False

    return True
Esempio n. 2
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: %s', name)
        log.error('nbr: %s', exc.winerror)
        log.error('ctx: %s', exc.funcname)
        log.error('msg: %s', 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: %s', exc.winerror)
        log.error('ctx: %s', exc.funcname)
        log.error('msg: %s', 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: %s', name)
                log.error('nbr: %s', exc.winerror)
                log.error('ctx: %s', exc.funcname)
                log.error('msg: %s', exc.strerror)
                return False
        else:
            log.error('User %s is currently logged in.', 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.args
            if number == 2:  # Profile Folder Not Found
                pass
            else:
                log.error('Failed to remove profile for %s', name)
                log.error('nbr: %s', exc.winerror)
                log.error('ctx: %s', exc.funcname)
                log.error('msg: %s', exc.strerror)
                return False

    # And finally remove the user account
    try:
        win32net.NetUserDel(None, name)
    except win32net.error as exc:
        log.error('Failed to delete user %s', name)
        log.error('nbr: %s', exc.winerror)
        log.error('ctx: %s', exc.funcname)
        log.error('msg: %s', exc.strerror)
        return False

    return True
Esempio n. 3
0
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 {}
Esempio n. 4
0
def update(name,
           password=None,
           fullname=None,
           description=None,
           home=None,
           homedrive=None,
           logonscript=None,
           profile=None,
           expiration_date=None,
           expired=None,
           account_disabled=None,
           unlock_account=None,
           password_never_expires=None,
           disallow_change_password=None):
    r'''
    Updates settings for the windows user. Name is the only required parameter.
    Settings will only be changed if the parameter is passed a value.

    .. versionadded:: 2015.8.0

    :param str name:
        The user name to update.

    :param str password:
        New user password in plain text.

    :param str fullname:
        The user's full name.

    :param str description:
        A brief description of the user account.

    :param str home:
        The path to the user's home directory.

    :param str homedrive:
        The drive letter to assign to the home directory. Must be the Drive Letter
        followed by a colon. ie: U:

    :param str logonscript:
        The path to the logon script.

    :param str profile:
        The path to the user's profile directory.

    :param date expiration_date: The date and time when the account expires. Can
        be a valid date/time string. To set to never expire pass the string 'Never'.

    :param bool expired: Pass `True` to expire the account. The user will be
        prompted to change their password at the next logon. Pass `False` to mark
        the account as 'not expired'. You can't use this to negate the expiration if
        the expiration was caused by the account expiring. You'll have to change
        the `expiration_date` as well.

    :param bool account_disabled: True disables the account. False enables the
        account.

    :param bool unlock_account: True unlocks a locked user account. False is
        ignored.

    :param bool password_never_expires: True sets the password to never expire.
        False allows the password to expire.

    :param bool disallow_change_password: True blocks the user from changing
        the password. False allows the user to change the password.

    :return: True if successful. False is unsuccessful.

    :rtype: bool

    CLI Example:

    .. code-block:: bash

        salt '*' user.update bob password=secret profile=C:\Users\Bob
                 home=\\server\homeshare\bob homedrive=U:
    '''

    # Make sure the user exists
    # Return an object containing current settings for the user
    try:
        user_info = win32net.NetUserGetInfo(None, name, 4)
    except win32net.error as exc:
        (number, context, message) = exc
        log.error('Failed to update user {0}'.format(name))
        log.error('nbr: {0}'.format(number))
        log.error('ctx: {0}'.format(context))
        log.error('msg: {0}'.format(message))
        return False

    # Check parameters to update
    # Update the user object with new settings
    if password:
        user_info['password'] = password
    if home:
        user_info['home_dir'] = home
    if homedrive:
        user_info['home_dir_drive'] = homedrive
    if description:
        user_info['comment'] = description
    if logonscript:
        user_info['script_path'] = logonscript
    if fullname:
        user_info['full_name'] = fullname
    if profile:
        user_info['profile'] = profile
    if expiration_date:
        if expiration_date == 'Never':
            user_info['acct_expires'] = win32netcon.TIMEQ_FOREVER
        else:
            try:
                dt_obj = salt.utils.date_cast(expiration_date)
            except (ValueError, RuntimeError):
                return 'Invalid Date/Time Format: {0}'.format(expiration_date)
            user_info['acct_expires'] = time.mktime(dt_obj.timetuple())
    if expired is not None:
        if expired:
            user_info['password_expired'] = 1
        else:
            user_info['password_expired'] = 0
    if account_disabled is not None:
        if account_disabled:
            user_info['flags'] |= win32netcon.UF_ACCOUNTDISABLE
        else:
            user_info['flags'] ^= win32netcon.UF_ACCOUNTDISABLE
    if unlock_account is not None:
        if unlock_account:
            user_info['flags'] ^= win32netcon.UF_LOCKOUT
    if password_never_expires is not None:
        if password_never_expires:
            user_info['flags'] |= win32netcon.UF_DONT_EXPIRE_PASSWD
        else:
            user_info['flags'] ^= win32netcon.UF_DONT_EXPIRE_PASSWD
    if disallow_change_password is not None:
        if disallow_change_password:
            user_info['flags'] |= win32netcon.UF_PASSWD_CANT_CHANGE
        else:
            user_info['flags'] ^= win32netcon.UF_PASSWD_CANT_CHANGE

    # Apply new settings
    try:
        win32net.NetUserSetInfo(None, name, 4, user_info)
    except win32net.error as exc:
        (number, context, message) = exc
        log.error('Failed to update 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
Esempio n. 5
0
def delete(name,
           purge=False,
           force=False):
    '''
    Remove a user from the minion

    :param str name:
        The name of the user to delete

    :param bool 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 bool 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.

    :return:
        True if successful
    :rtype: bool

    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:
        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(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
def getDomainUser(username, domain=None, info_level=0):
    if userExists(username, domain):
        return win32net.NetUserGetInfo(domain, username, info_level)
    else:
        return None
def userExists(username, domain=None):
    try:
        win32net.NetUserGetInfo(domain, username, 0)
        return True
    except:
        return False
Esempio n. 8
0
def startAutomation(**kwargs):

    # kwargs arguments.
    project = kwargs.get('project')
    test_run_id = kwargs.get('test_run_id')

    try:
        # Complete name (if is using the VPN).
        full_name = win32net.NetUserGetInfo(win32net.NetGetAnyDCName(),
                                            win32api.GetUserName(),
                                            2)["full_name"]
    except:
        # Windows login (if is not using the VPN).
        full_name = os.getlogin()

    try:
        testsetpathmanual = Aux.directories["EvidenceFolderManual"]
        Aux.createDirectory(testsetpathmanual)

        # Execute the action to get the manual evidences.
        test_case_id_list, n_iterations_list, id_azure_list, n_test_case_list = Azure.manualEvidences(
            project, test_run_id)

        for test_case_id in test_case_id_list:
            list_steps, name_testcase, summary, cont_steps, change_download_config = Azure.startSteps(
                project, test_case_id)
            step_initial = 0
            step_final = cont_steps
            n_print = 0
            n_iterations = n_iterations_list.pop(
                0)  # Get the number of the iterations for the test order.
            id_azure = id_azure_list.pop(0)
            n_test_case = n_test_case_list.pop(0)

            # Create the TestSet folder.
            testsetpath = os.path.join(
                Aux.directories["EvidenceFolder"],
                Aux.otherConfigs["ETSName"] + str(test_case_id) + " - " +
                name_testcase)
            if os.path.exists(testsetpath):
                shutil.rmtree(testsetpath)
            os.makedirs(testsetpath)
            Aux.addLogs("General", Aux.logs["EvidenceFolder"])
            Aux.createDirectory(testsetpath)

            print(
                f"{classes.Textcolor.WARNING}{Aux.otherConfigs['GeneratingEvidence']['Msg']}"
                f"{classes.Textcolor.END}\n")
            # Create an EST file.
            word_path = Aux.directories["ESTFile"] + ' ' + Aux.otherConfigs[
                "Language"] + '.docx'

            # Create evidence step by step per Iteration.
            for n_iteration in range(1, n_iterations + 1):
                # Move the prints to the correct folder and rename the evidences - Order by older first.
                filenames = os.listdir(Aux.directories["EvidenceFolderManual"])
                for filename in filenames:
                    if n_print == cont_steps: break
                    if (filename.endswith("png")) and \
                            (("CT" + str(n_test_case) + "-IT" + str(n_iteration)) in filename):

                        file_newname = 'Screenshot_' + str(n_print) + '.png'

                        # Rename the prints and move to the correct Test Case folder.
                        os.rename(
                            os.path.join(testsetpathmanual, filename),
                            os.path.join(testsetpathmanual, file_newname))
                        shutil.move(
                            os.path.join(testsetpathmanual, file_newname),
                            testsetpath)
                    n_print += 1
                n_print = 0

                est = Aux.wordAddSteps(
                    test_run_id, test_case_id,
                    name_testcase + " - ITERATION " + str(n_iteration),
                    summary, word_path, testsetpath,
                    list_steps[step_initial:step_final], "OK", full_name)
                if est is None:
                    Aux.addLogs(
                        "General", Aux.logs["ErrorEST"],
                        name_testcase + " - ITERATION " + str(n_iteration))

                pdf = Aux.wordToPDF(est)
                if pdf is None:
                    Aux.addLogs(
                        "General", Aux.logs["ErrorConvertPDF"],
                        name_testcase + " - ITERATION " + str(n_iteration))

                if (est is not None) and (pdf is not None):
                    # Add the evidence to the Run and the Test case.
                    Aux.addLogs(
                        "General", Aux.logs["ConvertPDF"],
                        name_testcase + " - ITERATION " + str(n_iteration))
                    Azure.SaveEvidenceRun(
                        project, test_run_id, id_azure,
                        Aux.directories["EvidenceFolder"],
                        Aux.otherConfigs["ETSName"] + str(test_case_id) +
                        " - " + name_testcase, n_iteration)
                    Azure.SaveEvidenceTestCase(
                        project, Aux.directories["EvidenceFolder"],
                        test_case_id, Aux.otherConfigs["ETSName"] +
                        str(test_case_id) + " - " + name_testcase, n_iteration)

                # Clear the evidences prints.
                Aux.deleteFiles(path_log=testsetpath, extension="png")

            n_test_case += 1

        shutil.rmtree(testsetpathmanual)

    except Exception as ex:
        print(
            f"{classes.Textcolor.FAIL}{Aux.logs['ErrorStartAutomation']['Msg']}{classes.Textcolor.END}",
            ex)
        Aux.addLogs("General", Aux.logs["ErrorStartAutomation"], str(ex))
        exit(1)

    Aux.addLogs("EndExecution")
Esempio n. 9
0
def get_display_name():
    user_info = win32net.NetUserGetInfo(win32net.NetGetAnyDCName(),
                                        win32api.GetUserName(), 2)
    fullname = user_info["full_name"]
    return fullname
Esempio n. 10
0
win32cred.CredWrite(cred)
pwd = None
print win32cred.CredRead(target, win32cred.CRED_TYPE_DOMAIN_PASSWORD)

## Marshal saved credential and use it to log on
mc = win32cred.CredMarshalCredential(win32cred.UsernameTargetCredential,
                                     target)
th = win32security.LogonUser(mc, None, '', win32con.LOGON32_LOGON_INTERACTIVE,
                             win32con.LOGON32_PROVIDER_DEFAULT)
win32security.ImpersonateLoggedOnUser(th)
print 'GetUserName:'******'s profile.  (first check if user has a roaming profile)
username, domain = win32cred.CredUIParseUserName(target)
user_info_4 = win32net.NetUserGetInfo(None, username, 4)
profilepath = user_info_4['profile']
## LoadUserProfile apparently doesn't like an empty string
if not profilepath:
    profilepath = None

## leave Flags in since 2.3 still chokes on some types of optional keyword args
hk = win32profile.LoadUserProfile(th, {
    'UserName': username,
    'Flags': 0,
    'ProfilePath': profilepath
})
## Get user's environment variables in a form that can be passed to win32process.CreateProcessAsUser
env = win32profile.CreateEnvironmentBlock(th, False)

## Cleanup should probably be in a finally block
def action(objectxmpp, action, sessionid, data, message, dataerreur):
    logging.getLogger().debug(
        "###################################################")
    logging.getLogger().debug("call %s from %s" % (plugin, message['from']))
    logging.getLogger().debug(
        "###################################################")
    dataerreur = {
        "action": "result" + action,
        "data": {
            "msg": "error plugin : " + action
        },
        'sessionid': sessionid,
        'ret': 255,
        'base64': False
    }

    if objectxmpp.config.agenttype in ['machine']:
        logging.getLogger().debug(
            "#######################################################")
        logging.getLogger().debug(
            "##############AGENT INSTALL KEY MACHINE################")
        logging.getLogger().debug(
            "#######################################################")
        if not 'key' in data:
            objectxmpp.send_message_agent(message['from'],
                                          dataerreur,
                                          mtype='chat')
            return
        #install keypub on AM
        if sys.platform.startswith('linux'):
            import pwd
            import grp
            #verify compte pulse exist
            try:
                uid = pwd.getpwnam("pulseuser").pw_uid
                gid = grp.getgrnam("pulseuser").gr_gid
                gidroot = grp.getgrnam("root").gr_gid
            except:
                #le compte n'existe pas
                result = simplecommand(
                    encode_strconsole(
                        "adduser --system --group --home /var/lib/pulse2 --shell /bin/rbash --disabled-password pulseuser"
                    ))
            uid = pwd.getpwnam("pulseuser").pw_uid
            gid = grp.getgrnam("pulseuser").gr_gid
            gidroot = grp.getgrnam("root").gr_gid
            authorized_keys_path = os.path.join(
                os.path.expanduser('~pulseuser'), '.ssh', 'authorized_keys')
            if not os.path.isdir(os.path.dirname(authorized_keys_path)):
                os.makedirs(os.path.dirname(authorized_keys_path), 0700)
            if not os.path.isfile(authorized_keys_path):
                file_put_contents(authorized_keys_path, "")
            os.chown(os.path.dirname(authorized_keys_path), uid, gid)
            os.chown(authorized_keys_path, uid, gid)
            os.chown(authorized_keys_path, uid, gid)
            packagepath = os.path.join(os.path.expanduser('~pulseuser'),
                                       'packages')
            pathuser = os.path.join(os.path.expanduser('~pulseuser'))
            if not os.path.isdir(pathuser):
                os.chmod(pathuser, 751)
            if not os.path.isdir(packagepath):
                os.makedirs(packagepath, 0764)
            os.chown(packagepath, uid, gidroot)
            os.chmod(os.path.dirname(authorized_keys_path), 0700)
            os.chmod(authorized_keys_path, 0644)
            os.chmod(packagepath, 0764)
            result = simplecommand(
                encode_strconsole("chown -R pulseuser: '******'"))
        elif sys.platform.startswith('win'):
            import win32net
            # check if pulse account exists
            try:
                win32net.NetUserGetInfo('', 'pulse', 0)
            except:
                # pulse account doesn't exist
                pulseuserpassword = uuid.uuid4().hex
                pulseuserhome = os.path.join(os.environ["ProgramFiles"],
                                             'Pulse')
                result = simplecommand(
                    encode_strconsole(
                        'net user "pulse" "%s" /ADD /COMMENT:"Pulse user with admin rights on the system" /PROFILEPATH:"%s"'
                        % (pulseuserpassword, pulseuserhome)))
                logging.getLogger().debug("Creation of pulse user: %s" %
                                          result)
            authorized_keys_path = os.path.join(os.environ["ProgramFiles"],
                                                'Pulse', '.ssh',
                                                'authorized_keys')
            if not os.path.isdir(os.path.dirname(authorized_keys_path)):
                os.makedirs(os.path.dirname(authorized_keys_path), 0700)
            if not os.path.isfile(authorized_keys_path):
                file_put_contents(authorized_keys_path, "")
            currentdir = os.getcwd()
            os.chdir(os.path.join(os.environ["ProgramFiles"], 'OpenSSH'))
            result = simplecommand(
                encode_strconsole(
                    'powershell -ExecutionPolicy Bypass -Command ". .\FixHostFilePermissions.ps1 -Confirm:$false"'
                ))
            os.chdir(currentdir)
            logging.getLogger().debug(
                "Reset of permissions on ssh keys and folders: %s" % result)
        elif sys.platform.startswith('darwin'):
            authorized_keys_path = os.path.join(
                os.path.join(os.path.expanduser('~pulse'), '.ssh',
                             'authorized_keys'))
        else:
            return

        authorized_keys_content = file_get_contents(authorized_keys_path)
        if not data['key'] in authorized_keys_content:
            #add en append la key dans le fichier
            file_put_contents_w_a(authorized_keys_path, data['key'], "a")
            logging.getLogger().debug("install key ARS [%s]" % message['from'])
            if sessionid.startswith("command"):
                notify = "Notify | QuickAction"
            else:
                notify = "Deployment | Cluster | Notify"

            objectxmpp.xmpplog('INSTALL key ARS %s on AM %s' %
                               (message['from'], objectxmpp.boundjid.bare),
                               type='deploy',
                               sessionname=sessionid,
                               priority=-1,
                               action="",
                               who=objectxmpp.boundjid.bare,
                               how="",
                               why="",
                               module=notify,
                               date=None,
                               fromuser="",
                               touser="")
        else:
            logging.getLogger().warning(
                "key ARS [%s] : is already installed." % message['from'])
            #if on veut que ce soit notifier dans le deployement
            #if sessionid.startswith("command"):
            #notify = "Notify | QuickAction"
            #else:
            #notify = "Deployment | Cluster | Notify"
            #objectxmpp.xmpplog("key ARS [%s] : is already installed on AM %s."%(message['from'], objectxmpp.boundjid.bare),
            #type = 'deploy',
            #sessionname = sessionid,
            #priority = -1,
            #action = "",
            #who = objectxmpp.boundjid.bare,
            #how = "",
            #why = "",
            #module = notify,
            #date = None ,
            #fromuser = "",
            #touser = "")
    else:
        logging.getLogger().debug(
            "#######################################################")
        logging.getLogger().debug(
            "##############AGENT RELAY SERVER KEY MACHINE###########")
        logging.getLogger().debug(
            "#######################################################")
        # send keupub ARM TO AM
        # ARM ONLY DEBIAN
        # lit la key Public
        key = ""
        key = file_get_contents(os.path.join('/', 'root', '.ssh',
                                             'id_rsa.pub'))
        if key == "":
            dataerreur['data'][
                'msg'] = "%s : KEY ARM MISSING" % dataerreur['data']['msg']
            objectxmpp.send_message_agent(message['from'],
                                          dataerreur,
                                          mtype='chat')
            return
        if not 'jidAM' in data:
            dataerreur['data'][
                'msg'] = "%s JID AM MISSING" % dataerreur['data']['msg']
            objectxmpp.send_message_agent(message['from'],
                                          dataerreur,
                                          mtype='chat')
            return

        datasend = {
            "action": action,
            "data": {
                "key": key
            },
            'sessionid': sessionid,
            'ret': 255,
            'base64': False
        }

        objectxmpp.send_message_agent(data['jidAM'], datasend, mtype='chat')
Esempio n. 12
0
def info(name):
    '''
    Return user information

    :param str name:
        Username for which to display information

    :returns:
        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
            - gid
    :rtype: dict

    CLI Example:

    .. code-block:: bash

        salt '*' user.info jsnuffy
    '''
    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
Esempio n. 13
0
def update(name,
           password=None,
           fullname=None,
           description=None,
           home=None,
           homedrive=None,
           logonscript=None,
           profile=None):
    r'''
    Updates settings for the windows user. Name is the only required parameter.
    Settings will only be changed if the parameter is passed a value.

    .. versionadded:: 2015.8.0

    :param str name:
        The user name to update.

    :param str password:
        New user password in plain text.

    :param str fullname:
        The user's full name.

    :param str description:
        A brief description of the user account.

    :param str home:
        The path to the user's home directory.

    :param str homedrive:
        The drive letter to assign to the home directory. Must be the Drive Letter
        followed by a colon. ie: U:

    :param str logonscript:
        The path to the logon script.

    :param str profile:
        The path to the user's profile directory.

    :return:
        True if successful. False is unsuccessful.
    :rtype: bool

    CLI Example:

    .. code-block:: bash

        salt '*' user.update bob password=secret profile=C:\Users\Bob
                 home=\\server\homeshare\bob homedrive=U:
    '''

    # Make sure the user exists
    # Return an object containing current settings for the user
    try:
        user_info = win32net.NetUserGetInfo(None, name, 4)
    except win32net.error as exc:
        (number, context, message) = exc
        log.error('Failed to update user {0}'.format(name))
        log.error('nbr: {0}'.format(number))
        log.error('ctx: {0}'.format(context))
        log.error('msg: {0}'.format(message))
        return False

    # Check parameters to update
    # Update the user object with new settings
    if password:
        user_info['password'] = password
    if home:
        user_info['home_dir'] = home
    if homedrive:
        user_info['home_dir_drive'] = homedrive
    if description:
        user_info['comment'] = description
    if logonscript:
        user_info['script_path'] = logonscript
    if fullname:
        user_info['full_name'] = fullname
    if profile:
        user_info['profile'] = profile

    # Apply new settings
    try:
        win32net.NetUserSetInfo(None, name, 4, user_info)
    except win32net.error as exc:
        (number, context, message) = exc
        log.error('Failed to update 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
Esempio n. 14
0
File: pb.py Progetto: Gumnos/pybug
#  DEFAULT_USER_DIR
#  DEFAULT_USER_CONFIG
#  DEFAULT_SYSTEM_DIR
##################################################
IS_WINDOWS = sys.platform.lower().startswith("win")

LOCAL_USER_ID = LOCAL_USERNAME = getpass.getuser()
LOCAL_USERNAME = LOCAL_USERNAME.title()
if IS_WINDOWS:
    try:
        # pylint: disable=F0401
        import win32net, win32api
        USER_INFO_20 = 20
        LOCAL_USERNAME = win32net.NetUserGetInfo(
            win32net.NetGetAnyDCName(),
            win32api.GetUserName(),
            USER_INFO_20,
            )["full_name"] or LOCAL_USERNAME
    except ImportError:
        pass
else:
    # pylint: disable=F0401
    import pwd # only available on non-win32
    LOCAL_USERNAME = pwd.getpwnam(LOCAL_USER_ID).pw_gecos.split(',', 1)[0]
LOCAL_EMAIL = (
    os.environ.get("EMAIL", "") or
    "%s@%s" % (LOCAL_USER_ID, gethostname())
    )

if IS_WINDOWS:
    DEFAULT_USER_DIR = os.path.join(
Esempio n. 15
0
def haveUser(user, servername=SERVERNAME):
    try:
        userinfo = win32net.NetUserGetInfo(servername, user, 0)
        return 1
    except win32net.error:
        return 0
Esempio n. 16
0
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 {}