Пример #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
Пример #2
0
def test_mo_to_xml():
    from imcsdk.mometa.aaa.AaaUser import AaaUser

    mo = AaaUser(parent_mo_or_dn='sys/user-ext', id='11')
    mo.name = 'abcd'
    mo.priv = 'admin'
    mo.pwd = 'abcd'
    xml = mo.to_xml()
    xml_str = xc.to_xml_str(xml)
    new_mo = xc.from_xml_str(xml_str)
    assert_equal(len(mo.__dict__), len(new_mo.__dict__))
    for prop in mo.__dict__:
        if prop == '_dirty_mask':
            continue
        assert_equal(getattr(mo, prop), getattr(new_mo, prop))
Пример #3
0
def test_002_create_specific_obj():
    # Create an object of type AaaUser with parent dn specified
    # check if the object has the right values populated
    from imcsdk.mometa.aaa.AaaUser import AaaUser
    obj = AaaUser(parent_mo_or_dn="sys/user-ext", id="10")
    assert_equal(obj.id, "10")
    assert_equal(obj.dn, "sys/user-ext/user-10")
Пример #4
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
Пример #5
0
def user_validate_inputs(**kwargs):
    """
    This method will check if the input parameters are valid
    """
    from imcsdk.mometa.aaa.AaaUser import AaaUser
    np = {}
    for prop in AaaUser.naming_props:
        if prop in kwargs:
            np[prop] = kwargs[prop]
    return AaaUser(parent_mo_or_dn=None, **np).validate_inputs(**kwargs)
Пример #6
0
def test_mo_to_xml():
    from imcsdk.mometa.aaa.AaaUser import AaaUser

    mo = AaaUser(parent_mo_or_dn='sys/user-ext', id='11')
    mo.name = 'abcd'
    mo.priv = 'admin'
    mo.pwd = 'abcd'
    xml = mo.to_xml()
    xml_str = xc.to_xml_str(xml)
    new_mo = xc.from_xml_str(xml_str.decode())
    assert_equal(len(mo.__dict__), len(new_mo.__dict__))
    for prop in mo.__dict__:
        if prop == '_dirty_mask':
            continue
        assert_equal(getattr(mo, prop), getattr(new_mo, prop))
Пример #7
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
Пример #8
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