Example #1
0
def local_user_create(handle,
                      name,
                      pwd,
                      priv="read-only",
                      account_status="active",
                      change_password=False):
    """
    This method will create a new local user and setup it's role.

    Args:
        handle (ImcHandle)
        name (string): username
        pwd (string): pwd
        priv (string): "admin", "read-only", "user"
        account_status (string): "active", "inactive"

    Returns:
        AaaUser object corresponding to the user created

    Raises:
        Exception when limit on the number of users has exceeded
    """

    from imcsdk.mometa.aaa.AaaUser import AaaUser

    # (1) local_user_exists(handle, name, pwd, priv) would be used by Ansible.
    # (2) local_user_exists(handle, name) would be used by user scripts.
    # If the privileges have changed for an existing user,
    #   (1) will fail, but (2) will pass.
    # In that case, Ansible will call local_user_create, which will fail
    # because user exists.Hence, special handling is needed in
    # local_user_exists to handle modify case.

    user = _get_local_user(handle, name)
    if user:
        pwd = pwd if change_password else None
        return local_user_modify(handle,
                                 name=name,
                                 pwd=pwd,
                                 priv=priv,
                                 account_status=account_status)

    available_user_id = _get_free_user_id(handle)

    new_user = AaaUser(parent_mo_or_dn="sys/user-ext", id=available_user_id)
    args = {
        "name": name,
        "pwd": pwd,
        "priv": priv,
        "account_status": account_status
    }
    new_user.set_prop_multiple(**args)

    handle.set_mo(new_user)
    return new_user
Example #2
0
def local_user_create(handle, name, pwd, priv="read-only",
                      account_status="active", change_password=False):
    """
    This method will create a new local user and setup it's role.

    Args:
        handle (ImcHandle)
        name (string): username
        pwd (string): pwd
        priv (string): "admin", "read-only", "user"
        account_status (string): "active", "inactive"

    Returns:
        AaaUser object corresponding to the user created

    Raises:
        Exception when limit on the number of users has exceeded
    """

    from imcsdk.mometa.aaa.AaaUser import AaaUser

    # (1) local_user_exists(handle, name, pwd, priv) would be used by Ansible.
    # (2) local_user_exists(handle, name) would be used by user scripts.
    # If the privileges have changed for an existing user,
    #   (1) will fail, but (2) will pass.
    # In that case, Ansible will call local_user_create, which will fail
    # because user exists.Hence, special handling is needed in
    # local_user_exists to handle modify case.

    user = _get_local_user(handle, name)
    if user:
        pwd = pwd if change_password else None
        return local_user_modify(handle, name=name, pwd=pwd, priv=priv,
                                 account_status=account_status)

    available_user_id = _get_free_user_id(handle)

    new_user = AaaUser(parent_mo_or_dn="sys/user-ext", id=available_user_id)
    args = {"name": name,
            "pwd": pwd,
            "priv": priv,
            "account_status": account_status}
    new_user.set_prop_multiple(**args)

    handle.set_mo(new_user)
    return new_user
Example #3
0
def local_users_update(handle, users=None):
    """
    This method will create, modify or delete local users.
    It could also be a combination of these operations.

    Args:
        handle (ImcHandle)
        users (list): list of user dict
          keys:
            name (string): username
            priv (string): "admin", "user", "read-only"
            pwd (string): password
            account_status(string): "active", "inactive"
            change_password(boolean): flag used to change password
          example:
            [{'name':'dummy',
              'pwd': '*****',
              'priv': 'admin',
              'change_password': true,
              'account_status': 'active'}]

    Returns:
        boolean: flag that indicates if users were created, modified or deleted. It could also be a combination of these operations.

    Raises:
        IMCOperationError for various failure scenarios. A sample IMC Exception looks something like this:
        "Update Local Users failed, error: User:dum1 - [ErrorCode]: 2003[ErrorDescription]: Operation failed. Matching old password(s), please enter a different password.;
    Note: This error msg format is being used in Cisco Intersight to map error messages to respective users. Please excercise caution before changing it in the API.
    """

    from imcsdk.mometa.aaa.AaaUser import AaaUser
    from imcsdk.imccoreutils import sanitize_message
    api = "Update Local Users"
    if users is None:
        users = []
    if len(users) > MAX_USERS:
        raise ImcOperationError(
            api, "Number of users exceeded max allowed limit on IMC")
    update_users = False
    create_users = False
    endpoint_users = _get_local_users(handle)
    used_ids, delete_users = _delete_users(handle, users, endpoint_users)
    all_ids = range(2, MAX_USERS + 1)
    free_ids = list(set(all_ids) - set(used_ids))
    create_mos = []
    modify_mos = []
    dn_to_user_dict = {}
    aaa_user_prefix = "sys/user-ext/user-"
    id = 0
    for user in users:
        if 'name' not in user:
            raise ImcOperationError(api, "User Name is invalid")
        if 'pwd' not in user:
            raise ImcOperationError(api, "Password is invalid")
        if 'priv' not in user:
            raise ImcOperationError(api, "Privilege is invalid")
        if 'account_status' not in user:
            account_status = "active"
        else:
            account_status = user['account_status']
        if 'change_password' not in user:
            change_password = False
        else:
            change_password = user['change_password']
        name = user['name']
        pwd = user['pwd']
        priv = user['priv']
        args = {
            "name": name,
            "pwd": pwd,
            "priv": priv,
            "account_status": account_status
        }

        # Existing users are not touched and hence we can safely check the
        # endpoint users list if there is
        found_user = None
        l = [x for x in endpoint_users if x.name == name]
        if len(l) != 0:
            found_user = l[0]
        if found_user:
            if not change_password:
                args.pop('pwd', None)
            if not found_user.check_prop_match(**args):
                update_users = True
            dn_to_user_dict[aaa_user_prefix + str(found_user.id)] = name
            found_user.set_prop_multiple(**args)
            modify_mos.append(found_user)
            continue
        if len(free_ids) == 0 or id >= len(free_ids):
            raise ImcOperationError(
                api, "Cannot configure more users than allowed limit on IMC")
        create_users = True
        free_id = free_ids[id]
        dn_to_user_dict[aaa_user_prefix + str(free_id)] = name
        mo = AaaUser(parent_mo_or_dn="sys/user-ext", id=str(free_id))
        mo.set_prop_multiple(**args)
        create_mos.append(mo)
        id += 1
    ret = []
    mos = []

    mos.extend(modify_mos)
    mos.extend(create_mos)

    response = handle.set_mos(mos)
    if response:
        ret = process_conf_mos_response(response, api, False,
                                        'Create/Update local users failed',
                                        user_mos_callback, dn_to_user_dict)
        if len(ret) != 0:
            error_msg = 'Create/Update local users failed:\n'
            for item in ret:
                user = item["Object"]
                error = item["Error"]
                error = sanitize_message(error)
                error_msg += user + ": " + error + "\n"

            raise ImcOperationErrorDetail(api, error_msg, ret)

    results = {}
    # print(create_users, update_users, delete_users)
    results["changed"] = create_users or update_users or delete_users
    results["msg"] = ""
    results["msg_params"] = ret

    return results
Example #4
0
def local_users_update(handle, users=None):
    """
    This method will create, modify or delete local users.
    It could also be a combination of these operations.

    Args:
        handle (ImcHandle)
        users (list): list of user dict
          keys:
            name (string): username
            priv (string): "admin", "user", "read-only"
            pwd (string): password
            account_status(string): "active", "inactive"
            change_password(boolean): flag used to change password
          example:
            [{'name':'dummy',
              'pwd': '*****',
              'priv': 'admin',
              'change_password': true,
              'account_status': 'active'}]

    Returns:
        boolean: flag that indicates if users were created, modified or deleted. It could also be a combination of these operations.

    Raises:
        IMCOperationError for various failure scenarios. A sample IMC Exception looks something like this:
        "Update Local Users failed, error: User:dum1 - [ErrorCode]: 2003[ErrorDescription]: Operation failed. Matching old password(s), please enter a different password.;
    """

    from imcsdk.mometa.aaa.AaaUser import AaaUser
    from imcsdk.imccoreutils import sanitize_message
    api = "Update Local Users"
    if users is None:
        raise ImcOperationError(api, "Users are invalid")
    if len(users) > MAX_USERS:
        raise ImcOperationError(api, "Number of users exceeded max allowed limit on IMC")
    update_users = False
    create_users = False
    endpoint_users = _get_local_users(handle)
    used_ids, delete_users = _delete_users(handle, users, endpoint_users)
    all_ids= range(2, MAX_USERS + 1)
    free_ids = list(set(all_ids) - set(used_ids))
    create_mos = []
    modify_mos = []
    dn_to_user_dict = {}
    aaa_user_prefix = "sys/user-ext/user-"
    id = 0
    for user in users:
        if 'name' not in user:
            raise ImcOperationError(api, "User Name is invalid")
        if 'pwd' not in user:
            raise ImcOperationError(api, "Password is invalid")
        if 'priv' not in user:
            raise ImcOperationError(api, "Privilege is invalid")
        if 'account_status' not in user:
            account_status = "active"
        else:
            account_status = user['account_status']
        if 'change_password' not in user:
            change_password = False
        else:
            change_password = user['change_password']
        name = user['name']
        pwd  = user['pwd']
        priv = user['priv']
        args = {"name": name,
                "pwd": pwd,
                "priv": priv,
                "account_status": account_status}

        # Existing users are not touched and hence we can safely check the
        # endpoint users list if there is
        found_user = None
        l = [x for x in endpoint_users if x.name == name]
        if len(l) != 0:
            found_user = l[0]
        if found_user:
            if not change_password:
                args.pop('pwd', None)
            if not found_user.check_prop_match(**args):
                update_users = True
            dn_to_user_dict[aaa_user_prefix+str(found_user.id)] = name
            found_user.set_prop_multiple(**args)
            modify_mos.append(found_user)
            continue
        if len(free_ids) == 0 or id >= len(free_ids):
            raise ImcOperationError(api,"Cannot configure more users than allowed limit on IMC")
        create_users = True
        free_id = free_ids[id]
        dn_to_user_dict[aaa_user_prefix+str(free_id)] = name
        mo = AaaUser(parent_mo_or_dn="sys/user-ext", id=str(free_id))
        mo.set_prop_multiple(**args)
        create_mos.append(mo)
        id += 1
    ret = []
    mos = []

    mos.extend(modify_mos)
    mos.extend(create_mos)

    response = handle.set_mos(mos)
    if response:
        ret = process_conf_mos_response(response, api, False,
                                        'Create/Update local users failed',
                                        user_mos_callback,
                                        dn_to_user_dict)
        if len(ret) != 0:
            error_msg = 'Create/Update local users failed:\n'
            for item in ret:
                user = item["Object"]
                error = item["Error"]
                error = sanitize_message(error)
                error_msg += user + ": " + error + "\n"

            raise ImcOperationErrorDetail(api, error_msg, ret)

    results = {}
    # print(create_users, update_users, delete_users)
    results["changed"] = create_users or update_users or delete_users
    results["msg"] = ""
    results["msg_params"] = ret

    return results