当前位置: 首页>>代码示例>>Python>>正文


Python SamDB.modify方法代码示例

本文整理汇总了Python中samba.samdb.SamDB.modify方法的典型用法代码示例。如果您正苦于以下问题:Python SamDB.modify方法的具体用法?Python SamDB.modify怎么用?Python SamDB.modify使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在samba.samdb.SamDB的用法示例。


在下文中一共展示了SamDB.modify方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: run

# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import modify [as 别名]
    def run(self, accountname, principal, credopts=None, sambaopts=None, versionopts=None):

        lp = sambaopts.get_loadparm()
        creds = credopts.get_credentials(lp)
        paths = provision.provision_paths_from_lp(lp, lp.get("realm"))
        sam = SamDB(paths.samdb, session_info=system_session(),
                    credentials=creds, lp=lp)
        # TODO once I understand how, use the domain info to naildown
        # to the correct domain
        (cleanedaccount, realm, domain) = _get_user_realm_domain(accountname)

        res = sam.search(expression="sAMAccountName=%s" % cleanedaccount,
                            scope=ldb.SCOPE_SUBTREE,
                            attrs=["msDS-AllowedToDelegateTo"])
        if len(res) != 1:
            raise CommandError("Account %s found %d times" % (accountname, len(res)))

        msg = ldb.Message()
        msg.dn = res[0].dn
        msg["msDS-AllowedToDelegateTo"] = ldb.MessageElement([principal],
                                              ldb.FLAG_MOD_ADD,
                                              "msDS-AllowedToDelegateTo")
        try:
            sam.modify(msg)
        except Exception, err:
            raise CommandError(err)
开发者ID:Arkhont,项目名称:samba,代码行数:28,代码来源:delegation.py

示例2: run

# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import modify [as 别名]
    def run(self, accountname, principal, H=None, credopts=None, sambaopts=None,
            versionopts=None):

        lp = sambaopts.get_loadparm()
        creds = credopts.get_credentials(lp)
        paths = provision.provision_paths_from_lp(lp, lp.get("realm"))
        if H == None:
            path = paths.samdb
        else:
            path = H

        sam = SamDB(path, session_info=system_session(),
                    credentials=creds, lp=lp)
        # TODO once I understand how, use the domain info to naildown
        # to the correct domain
        (cleanedaccount, realm, domain) = _get_user_realm_domain(accountname)

        res = sam.search(expression="sAMAccountName=%s" %
                         ldb.binary_encode(cleanedaccount),
                         scope=ldb.SCOPE_SUBTREE,
                         attrs=["msDS-AllowedToDelegateTo"])
        if len(res) == 0:
            raise CommandError("Unable to find account name '%s'" % accountname)
        assert(len(res) == 1)

        msg = ldb.Message()
        msg.dn = res[0].dn
        msg["msDS-AllowedToDelegateTo"] = ldb.MessageElement([principal],
                                          ldb.FLAG_MOD_DELETE,
                                          "msDS-AllowedToDelegateTo")
        try:
            sam.modify(msg)
        except Exception as err:
            raise CommandError(err)
开发者ID:Alexander--,项目名称:samba,代码行数:36,代码来源:delegation.py

示例3: test_modify_replicated_attributes

# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import modify [as 别名]
    def test_modify_replicated_attributes(self):
        # some timestamp ones
        dn = 'CN=Guest,CN=Users,' + self.base_dn
        value = 'hallooo'
        for attr in ['carLicense', 'middleName']:
            msg = ldb.Message()
            msg.dn = ldb.Dn(self.samdb, dn)
            msg[attr] = ldb.MessageElement(value,
                                           ldb.FLAG_MOD_REPLACE,
                                           attr)
            try:
                self.samdb.modify(msg)
                self.fail("Failed to fail to modify %s %s" % (dn, attr))
            except ldb.LdbError as e1:
                (ecode, emsg) = e1.args
                if ecode != ldb.ERR_REFERRAL:
                    self.fail("Failed to REFER when trying to modify %s %s" %
                              (dn, attr))
                else:
                    m = re.search(r'(ldap://[^>]+)>', emsg)
                    if m is None:
                        self.fail("referral seems not to refer to anything")
                    address = m.group(1)

                    try:
                        tmpdb = SamDB(address, credentials=CREDS,
                                      session_info=system_session(LP), lp=LP)
                        tmpdb.modify(msg)
                    except ldb.LdbError as e:
                        self.fail("couldn't modify referred location %s" %
                                  address)

                    if address.lower().startswith(self.samdb.domain_dns_name()):
                        self.fail("referral address did not give a specific DC")
开发者ID:DavidMulder,项目名称:samba,代码行数:36,代码来源:rodc.py

示例4: run

# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import modify [as 别名]
    def run(self, psoname, H=None, precedence=None, min_pwd_age=None,
            max_pwd_age=None, complexity=None, store_plaintext=None,
            history_length=None, min_pwd_length=None,
            account_lockout_duration=None, account_lockout_threshold=None,
            reset_account_lockout_after=None, credopts=None, sambaopts=None,
            versionopts=None):
        lp = sambaopts.get_loadparm()
        creds = credopts.get_credentials(lp)

        samdb = SamDB(url=H, session_info=system_session(),
            credentials=creds, lp=lp)

        # sanity-check the PSO exists
        pso_dn = "CN=%s,%s" % (psoname, pso_container(samdb))
        check_pso_valid(samdb, pso_dn, psoname)

        # we expect the user to specify at least one password-policy setting
        num_pwd_args = num_options_in_args(pwd_settings_options, self.raw_argv)
        if num_pwd_args == 0 and precedence is None:
            raise CommandError("Please specify at least one password policy setting. Try --help")

        if min_pwd_age is not None or max_pwd_age is not None:
            # if we're modifying either the max or min pwd-age, check the max is
            # always larger. We may have to fetch the PSO's setting to verify this
            res = samdb.search(pso_dn, scope=ldb.SCOPE_BASE,
                               attrs=['msDS-MinimumPasswordAge',
                                      'msDS-MaximumPasswordAge'])
            if min_pwd_age is None:
                min_pwd_age = timestamp_to_days(res[0]['msDS-MinimumPasswordAge'][0])

            if max_pwd_age is None:
                max_pwd_age = timestamp_to_days(res[0]['msDS-MaximumPasswordAge'][0])

        check_pso_constraints(max_pwd_age=max_pwd_age, min_pwd_age=min_pwd_age,
                              history_length=history_length,
                              min_pwd_length=min_pwd_length)

        # pack the settings into an LDB message
        m = make_pso_ldb_msg(self.outf, samdb, pso_dn, create=False,
                             complexity=complexity, precedence=precedence,
                             store_plaintext=store_plaintext,
                             history_length=history_length,
                             min_pwd_length=min_pwd_length,
                             min_pwd_age=min_pwd_age, max_pwd_age=max_pwd_age,
                             lockout_duration=account_lockout_duration,
                             lockout_threshold=account_lockout_threshold,
                             reset_account_lockout_after=reset_account_lockout_after)

        # update the PSO
        try:
            samdb.modify(m)
            self.message("Successfully updated PSO: %s" % pso_dn)
            # display the new PSO's settings
            show_pso_by_dn(self.outf, samdb, pso_dn, show_applies_to=False)
        except ldb.LdbError as e:
            (num, msg) = e.args
            raise CommandError("Failed to update PSO '%s': %s" %(pso_dn, msg))
开发者ID:Alexander--,项目名称:samba,代码行数:59,代码来源:pso.py

示例5: test_offline_manual_seized_ridalloc_with_dbcheck

# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import modify [as 别名]
    def test_offline_manual_seized_ridalloc_with_dbcheck(self):
        """Peform the same actions as test_offline_samba_tool_seized_ridalloc,
        but do not create the RID set. Confirm that dbcheck correctly creates
        the RID Set.

        Also check
        """
        fsmo_dn = ldb.Dn(self.ldb_dc1, "CN=RID Manager$,CN=System," + self.ldb_dc1.domain_dn())
        (fsmo_owner, fsmo_not_owner) = self._determine_fSMORoleOwner(fsmo_dn)

        targetdir = self._test_join(fsmo_not_owner['dns_name'], "RIDALLOCTEST2")
        try:
            # Connect to the database
            ldb_url = "tdb://%s" % os.path.join(targetdir, "private/sam.ldb")
            lp = self.get_loadparm()

            new_ldb = SamDB(ldb_url, credentials=self.get_credentials(),
                            session_info=system_session(lp), lp=lp)

            serviceName = new_ldb.get_dsServiceName()
            m = ldb.Message()
            m.dn = fsmo_dn
            m["fSMORoleOwner"] = ldb.MessageElement(serviceName,
                                                   ldb.FLAG_MOD_REPLACE,
                                                   "fSMORoleOwner")
            new_ldb.modify(m)

            # 1. Get server name
            res = new_ldb.search(base=ldb.Dn(new_ldb, new_ldb.get_serverName()),
                                 scope=ldb.SCOPE_BASE, attrs=["serverReference"])
            # 2. Get server reference
            server_ref_dn = ldb.Dn(new_ldb, res[0]['serverReference'][0])

            # Assert that no RID Set has been set
            res = new_ldb.search(base=server_ref_dn,
                                 scope=ldb.SCOPE_BASE, attrs=['rIDSetReferences'])

            self.assertFalse("rIDSetReferences" in res[0])

            smbconf = os.path.join(targetdir, "etc/smb.conf")

            chk = dbcheck(new_ldb, verbose=False, fix=True, yes=True, quiet=True)

            self.assertEqual(chk.check_database(DN=server_ref_dn, scope=ldb.SCOPE_BASE), 1, "Should have fixed one error (missing RID Set)")

            # 3. Assert we get the RID Set
            res = new_ldb.search(base=server_ref_dn,
                                 scope=ldb.SCOPE_BASE, attrs=['rIDSetReferences'])

            self.assertTrue("rIDSetReferences" in res[0])
        finally:
            self._test_force_demote(fsmo_not_owner['dns_name'], "RIDALLOCTEST2")
            shutil.rmtree(targetdir, ignore_errors=True)
开发者ID:samba-team,项目名称:samba,代码行数:55,代码来源:ridalloc_exop.py

示例6: test_offline_manual_seized_ridalloc_add_user_as_admin

# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import modify [as 别名]
    def test_offline_manual_seized_ridalloc_add_user_as_admin(self):
        """Peform the same actions as test_offline_samba_tool_seized_ridalloc,
        but do not create the RID set. Confirm that user-add correctly creates
        the RID Set."""
        fsmo_dn = ldb.Dn(self.ldb_dc1, "CN=RID Manager$,CN=System," + self.ldb_dc1.domain_dn())
        (fsmo_owner, fsmo_not_owner) = self._determine_fSMORoleOwner(fsmo_dn)

        targetdir = self._test_join(fsmo_not_owner['dns_name'], "RIDALLOCTEST4")
        try:
            # Connect to the database
            ldb_url = "tdb://%s" % os.path.join(targetdir, "private/sam.ldb")
            lp = self.get_loadparm()

            new_ldb = SamDB(ldb_url, credentials=self.get_credentials(),
                            session_info=admin_session(lp, self.ldb_dc1.get_domain_sid()), lp=lp)

            serviceName = new_ldb.get_dsServiceName()
            m = ldb.Message()
            m.dn = fsmo_dn
            m["fSMORoleOwner"] = ldb.MessageElement(serviceName,
                                                   ldb.FLAG_MOD_REPLACE,
                                                   "fSMORoleOwner")
            new_ldb.modify(m)

            # 1. Get server name
            res = new_ldb.search(base=ldb.Dn(new_ldb, new_ldb.get_serverName()),
                                 scope=ldb.SCOPE_BASE, attrs=["serverReference"])
            # 2. Get server reference
            server_ref_dn = ldb.Dn(new_ldb, res[0]['serverReference'][0])

            # Assert that no RID Set has been set
            res = new_ldb.search(base=server_ref_dn,
                                 scope=ldb.SCOPE_BASE, attrs=['rIDSetReferences'])

            self.assertFalse("rIDSetReferences" in res[0])

            smbconf = os.path.join(targetdir, "etc/smb.conf")

            # Create a user to allocate a RID Set for itself (the RID master)
            new_ldb.newuser("ridalloctestuser", "[email protected]!")

            # 3. Assert we get the RID Set
            res = new_ldb.search(base=server_ref_dn,
                                 scope=ldb.SCOPE_BASE, attrs=['rIDSetReferences'])

            self.assertTrue("rIDSetReferences" in res[0])

        finally:
            self._test_force_demote(fsmo_not_owner['dns_name'], "RIDALLOCTEST4")
            shutil.rmtree(targetdir, ignore_errors=True)
开发者ID:samba-team,项目名称:samba,代码行数:52,代码来源:ridalloc_exop.py

示例7: run

# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import modify [as 别名]
    def run(self, name, user=None, credopts=None, sambaopts=None,
            versionopts=None):
        lp = sambaopts.get_loadparm()
        creds = credopts.get_credentials(lp)
        paths = provision.provision_paths_from_lp(lp, lp.get("realm"))
        sam = SamDB(paths.samdb, session_info=system_session(),
                    credentials=creds, lp=lp)
        res = sam.search(
            expression="servicePrincipalName=%s" % ldb.binary_encode(name),
            scope=ldb.SCOPE_SUBTREE,
            attrs=["servicePrincipalName", "samAccountName"])
        if len(res) >0:
            result = None
            if user is not None:
                (cleaneduser, realm, domain) = _get_user_realm_domain(user)
                for elem in res:
                    if str(elem["samAccountName"]).lower() == cleaneduser:
                        result = elem
                if result is None:
                    raise CommandError("Unable to find user %s with"
                                           " spn %s" % (user, name))
            else:
                if len(res) != 1:
                    listUser = ""
                    for r in res:
                        listUser = "%s\n%s" % (listUser, str(r.dn))
                    raise CommandError("More than one user has the spn %s "
                           "and no specific user was specified, list of users"
                           " with this spn:%s" % (name, listUser))
                else:
                    result=res[0]


            msg = ldb.Message()
            spns = result.get("servicePrincipalName")
            tab = []
            if spns is not None:
                for e in spns:
                    if str(e) != name:
                        tab.append(str(e))
                flag = ldb.FLAG_MOD_REPLACE
            msg.dn = result.dn
            msg["servicePrincipalName"] = ldb.MessageElement(tab, flag,
                                            "servicePrincipalName")
            sam.modify(msg)
        else:
            raise CommandError("Service principal %s not affected" % name)
开发者ID:sYnfo,项目名称:samba,代码行数:49,代码来源:spn.py

示例8: run

# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import modify [as 别名]
    def run(self, value, H=None, credopts=None, sambaopts=None, versionopts=None):
        lp = sambaopts.get_loadparm()
        creds = credopts.get_credentials(lp)

        samdb = SamDB(url=H, session_info=system_session(),
            credentials=creds, lp=lp)

        domain_dn = samdb.domain_dn()
        object_dn = "%s,%s" % (self.objectdn, domain_dn)

        # Create the modification
        m = ldb.Message()
        m.dn = ldb.Dn(samdb, object_dn)
        m[self.attribute] = ldb.MessageElement(
            value, ldb.FLAG_MOD_REPLACE, self.attribute)

        samdb.modify(m)
        self.outf.write("set %s: %s\n" % (self.attribute, value))
开发者ID:Alexander--,项目名称:samba,代码行数:20,代码来源:forest.py

示例9: run

# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import modify [as 别名]
    def run(self, attribute, H=None, credopts=None, sambaopts=None,
            versionopts=None, searchflags=None):

        if searchflags is None:
            raise CommandError('A value to modify must be provided.')

        # Parse the search flags to a set of bits to modify.

        searchflags_int = None
        if searchflags is not None:
            searchflags_int = 0
            flags = searchflags.split(',')
            # We have to normalise all the values. To achieve this predictably
            # we title case (Fattrindex), then swapcase (fATTINDEX)
            flags = [ x.capitalize().swapcase() for x in flags ]
            for flag in flags:
                if flag not in bitFields['searchflags'].keys():
                    raise CommandError("Unknown flag '%s', please see --help" % flag)
                bit_loc = 31 - bitFields['searchflags'][flag]
                # Now apply the bit.
                searchflags_int = searchflags_int | (1 << bit_loc)

        lp = sambaopts.get_loadparm()
        creds = credopts.get_credentials(lp)

        samdb = SamDB(url=H, session_info=system_session(),
            credentials=creds, lp=lp)

        schema_dn = samdb.schema_dn()
        # For now we make assumptions about the CN
        attr_dn = 'cn=%s,%s' % (attribute, schema_dn)

        m = ldb.Message()
        m.dn = ldb.Dn(samdb, attr_dn)

        if searchflags_int is not None:
            m['searchFlags'] = ldb.MessageElement(
                str(searchflags_int), ldb.FLAG_MOD_REPLACE, 'searchFlags')

        samdb.modify(m)
        samdb.set_schema_update_now()
        self.outf.write("modified %s" % attr_dn)
开发者ID:Alexander--,项目名称:samba,代码行数:44,代码来源:schema.py

示例10: run

# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import modify [as 别名]

#.........这里部分代码省略.........
            cur_min_pwd_len = int(res[0]["minPwdLength"][0])
            # ticks -> days
            cur_min_pwd_age = int(abs(int(res[0]["minPwdAge"][0])) / (1e7 * 60 * 60 * 24))
            cur_max_pwd_age = int(abs(int(res[0]["maxPwdAge"][0])) / (1e7 * 60 * 60 * 24))
        except KeyError:
            raise CommandError("Could not retrieve password properties!")

        if subcommand == "show":
            self.message("Password informations for domain '%s'" % domain_dn)
            self.message("")
            if pwd_props & DOMAIN_PASSWORD_COMPLEX != 0:
                self.message("Password complexity: on")
            else:
                self.message("Password complexity: off")
            self.message("Password history length: %d" % pwd_hist_len)
            self.message("Minimum password length: %d" % cur_min_pwd_len)
            self.message("Minimum password age (days): %d" % cur_min_pwd_age)
            self.message("Maximum password age (days): %d" % cur_max_pwd_age)
        elif subcommand == "set":
            msgs = []
            m = ldb.Message()
            m.dn = ldb.Dn(samdb, domain_dn)

            if complexity is not None:
                if complexity == "on" or complexity == "default":
                    pwd_props = pwd_props | DOMAIN_PASSWORD_COMPLEX
                    msgs.append("Password complexity activated!")
                elif complexity == "off":
                    pwd_props = pwd_props & (~DOMAIN_PASSWORD_COMPLEX)
                    msgs.append("Password complexity deactivated!")

                m["pwdProperties"] = ldb.MessageElement(str(pwd_props),
                  ldb.FLAG_MOD_REPLACE, "pwdProperties")

            if history_length is not None:
                if history_length == "default":
                    pwd_hist_len = 24
                else:
                    pwd_hist_len = int(history_length)

                if pwd_hist_len < 0 or pwd_hist_len > 24:
                    raise CommandError("Password history length must be in the range of 0 to 24!")

                m["pwdHistoryLength"] = ldb.MessageElement(str(pwd_hist_len),
                  ldb.FLAG_MOD_REPLACE, "pwdHistoryLength")
                msgs.append("Password history length changed!")

            if min_pwd_length is not None:
                if min_pwd_length == "default":
                    min_pwd_len = 7
                else:
                    min_pwd_len = int(min_pwd_length)

                if min_pwd_len < 0 or min_pwd_len > 14:
                    raise CommandError("Minimum password length must be in the range of 0 to 14!")

                m["minPwdLength"] = ldb.MessageElement(str(min_pwd_len),
                  ldb.FLAG_MOD_REPLACE, "minPwdLength")
                msgs.append("Minimum password length changed!")

            if min_pwd_age is not None:
                if min_pwd_age == "default":
                    min_pwd_age = 0
                else:
                    min_pwd_age = int(min_pwd_age)

                if min_pwd_age < 0 or min_pwd_age > 998:
                    raise CommandError("Minimum password age must be in the range of 0 to 998!")

                # days -> ticks
                min_pwd_age_ticks = -int(min_pwd_age * (24 * 60 * 60 * 1e7))

                m["minPwdAge"] = ldb.MessageElement(str(min_pwd_age_ticks),
                  ldb.FLAG_MOD_REPLACE, "minPwdAge")
                msgs.append("Minimum password age changed!")

            if max_pwd_age is not None:
                if max_pwd_age == "default":
                    max_pwd_age = 43
                else:
                    max_pwd_age = int(max_pwd_age)

                if max_pwd_age < 0 or max_pwd_age > 999:
                    raise CommandError("Maximum password age must be in the range of 0 to 999!")

                # days -> ticks
                max_pwd_age_ticks = -int(max_pwd_age * (24 * 60 * 60 * 1e7))

                m["maxPwdAge"] = ldb.MessageElement(str(max_pwd_age_ticks),
                  ldb.FLAG_MOD_REPLACE, "maxPwdAge")
                msgs.append("Maximum password age changed!")

            if max_pwd_age > 0 and min_pwd_age >= max_pwd_age:
                raise CommandError("Maximum password age (%d) must be greater than minimum password age (%d)!" % (max_pwd_age, min_pwd_age))

            samdb.modify(m)
            msgs.append("All changes applied successfully!")
            self.message("\n".join(msgs))
        else:
            raise CommandError("Wrong argument '%s'!" % subcommand)
开发者ID:endisd,项目名称:samba,代码行数:104,代码来源:pwsettings.py

示例11: GroupAuditTests

# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import modify [as 别名]

#.........这里部分代码省略.........
        # before there primary group can be set to that group.
        #
        self.discardMessages()

        self.ldb.add_remove_group_members(GROUP_NAME_01, [USER_NAME])
        messages = self.waitForMessages(1)
        print("Received %d messages" % len(messages))
        self.assertEquals(1,
                          len(messages),
                          "Did not receive the expected number of messages")
        audit = messages[0]["groupChange"]

        self.assertEqual("Added", audit["action"])
        user_dn = "cn=" + USER_NAME + ",cn=users," + self.base_dn
        group_dn = "cn=" + GROUP_NAME_01 + ",cn=users," + self.base_dn
        self.assertTrue(user_dn.lower(), audit["user"].lower())
        self.assertTrue(group_dn.lower(), audit["group"].lower())
        self.assertRegexpMatches(audit["remoteAddress"],
                                 self.remoteAddress)
        self.assertTrue(self.is_guid(audit["sessionId"]))
        session_id = self.get_session()
        self.assertEquals(session_id, audit["sessionId"])
        service_description = self.get_service_description()
        self.assertEquals(service_description, "LDAP")

        #
        # Change the primary group of a user
        #
        user_dn = "cn=" + USER_NAME + ",cn=users," + self.base_dn
        group_dn = "cn=" + GROUP_NAME_01 + ",cn=users," + self.base_dn
        # get the primaryGroupToken of the group
        res = self.ldb.search(base=group_dn, attrs=["primaryGroupToken"],
                              scope=ldb.SCOPE_BASE)
        group_id = res[0]["primaryGroupToken"]

        # set primaryGroupID attribute of the user to that group
        m = ldb.Message()
        m.dn = ldb.Dn(self.ldb, user_dn)
        m["primaryGroupID"] = ldb.MessageElement(
            group_id,
            FLAG_MOD_REPLACE,
            "primaryGroupID")
        self.discardMessages()
        self.ldb.modify(m)

        #
        # Wait for the primary group change.
        # Will see the user removed from the new group
        #          the user added to their old primary group
        #          and a new primary group event.
        #
        messages = self.waitForMessages(3)
        print("Received %d messages" % len(messages))
        self.assertEquals(3,
                          len(messages),
                          "Did not receive the expected number of messages")

        audit = messages[0]["groupChange"]
        self.assertEqual("Removed", audit["action"])
        user_dn = "cn=" + USER_NAME + ",cn=users," + self.base_dn
        group_dn = "cn=" + GROUP_NAME_01 + ",cn=users," + self.base_dn
        self.assertTrue(user_dn.lower(), audit["user"].lower())
        self.assertTrue(group_dn.lower(), audit["group"].lower())
        self.assertRegexpMatches(audit["remoteAddress"],
                                 self.remoteAddress)
        self.assertTrue(self.is_guid(audit["sessionId"]))
        session_id = self.get_session()
        self.assertEquals(session_id, audit["sessionId"])
        service_description = self.get_service_description()
        self.assertEquals(service_description, "LDAP")

        audit = messages[1]["groupChange"]

        self.assertEqual("Added", audit["action"])
        user_dn = "cn=" + USER_NAME + ",cn=users," + self.base_dn
        group_dn = "cn=domain users,cn=users," + self.base_dn
        self.assertTrue(user_dn.lower(), audit["user"].lower())
        self.assertTrue(group_dn.lower(), audit["group"].lower())
        self.assertRegexpMatches(audit["remoteAddress"],
                                 self.remoteAddress)
        self.assertTrue(self.is_guid(audit["sessionId"]))
        session_id = self.get_session()
        self.assertEquals(session_id, audit["sessionId"])
        service_description = self.get_service_description()
        self.assertEquals(service_description, "LDAP")

        audit = messages[2]["groupChange"]

        self.assertEqual("PrimaryGroup", audit["action"])
        user_dn = "cn=" + USER_NAME + ",cn=users," + self.base_dn
        group_dn = "cn=" + GROUP_NAME_01 + ",cn=users," + self.base_dn
        self.assertTrue(user_dn.lower(), audit["user"].lower())
        self.assertTrue(group_dn.lower(), audit["group"].lower())
        self.assertRegexpMatches(audit["remoteAddress"],
                                 self.remoteAddress)
        self.assertTrue(self.is_guid(audit["sessionId"]))
        session_id = self.get_session()
        self.assertEquals(session_id, audit["sessionId"])
        service_description = self.get_service_description()
        self.assertEquals(service_description, "LDAP")
开发者ID:Alexander--,项目名称:samba,代码行数:104,代码来源:group_audit.py

示例12: run

# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import modify [as 别名]

#.........这里部分代码省略.........
            if level_forest == DS_DOMAIN_FUNCTION_2000:
                outstr = "2000"
            elif level_forest == DS_DOMAIN_FUNCTION_2003_MIXED:
                outstr = "2003 with mixed domains/interim (NT4 DC support)"
            elif level_forest == DS_DOMAIN_FUNCTION_2003:
                outstr = "2003"
            elif level_forest == DS_DOMAIN_FUNCTION_2008:
                outstr = "2008"
            elif level_forest == DS_DOMAIN_FUNCTION_2008_R2:
                outstr = "2008 R2"
            else:
                outstr = "higher than 2008 R2"
            self.message("Forest function level: (Windows) " + outstr)

            if level_domain == DS_DOMAIN_FUNCTION_2000 and level_domain_mixed != 0:
                outstr = "2000 mixed (NT4 DC support)"
            elif level_domain == DS_DOMAIN_FUNCTION_2000 and level_domain_mixed == 0:
                outstr = "2000"
            elif level_domain == DS_DOMAIN_FUNCTION_2003_MIXED:
                outstr = "2003 with mixed domains/interim (NT4 DC support)"
            elif level_domain == DS_DOMAIN_FUNCTION_2003:
                outstr = "2003"
            elif level_domain == DS_DOMAIN_FUNCTION_2008:
                outstr = "2008"
            elif level_domain == DS_DOMAIN_FUNCTION_2008_R2:
                outstr = "2008 R2"
            else:
                outstr = "higher than 2008 R2"
            self.message("Domain function level: (Windows) " + outstr)

            if min_level_dc == DS_DOMAIN_FUNCTION_2000:
                outstr = "2000"
            elif min_level_dc == DS_DOMAIN_FUNCTION_2003:
                outstr = "2003"
            elif min_level_dc == DS_DOMAIN_FUNCTION_2008:
                outstr = "2008"
            elif min_level_dc == DS_DOMAIN_FUNCTION_2008_R2:
                outstr = "2008 R2"
            else:
                outstr = "higher than 2008 R2"
            self.message("Lowest function level of a DC: (Windows) " + outstr)

        elif subcommand == "raise":
            msgs = []

            if domain_level is not None:
                if domain_level == "2003":
                    new_level_domain = DS_DOMAIN_FUNCTION_2003
                elif domain_level == "2008":
                    new_level_domain = DS_DOMAIN_FUNCTION_2008
                elif domain_level == "2008_R2":
                    new_level_domain = DS_DOMAIN_FUNCTION_2008_R2

                if new_level_domain <= level_domain and level_domain_mixed == 0:
                    raise CommandError("Domain function level can't be smaller than or equal to the actual one!")

                if new_level_domain > min_level_dc:
                    raise CommandError("Domain function level can't be higher than the lowest function level of a DC!")

                # Deactivate mixed/interim domain support
                if level_domain_mixed != 0:
                    # Directly on the base DN
                    m = ldb.Message()
                    m.dn = ldb.Dn(samdb, domain_dn)
                    m["nTMixedDomain"] = ldb.MessageElement("0",
                      ldb.FLAG_MOD_REPLACE, "nTMixedDomain")
                    samdb.modify(m)
                    # Under partitions
                    m = ldb.Message()
                    m.dn = ldb.Dn(samdb, "CN=" + lp.get("workgroup") + ",CN=Partitions,%s" % samdb.get_config_basedn())
                    m["nTMixedDomain"] = ldb.MessageElement("0",
                      ldb.FLAG_MOD_REPLACE, "nTMixedDomain")
                    try:
                        samdb.modify(m)
                    except ldb.LdbError, (enum, emsg):
                        if enum != ldb.ERR_UNWILLING_TO_PERFORM:
                            raise

                # Directly on the base DN
                m = ldb.Message()
                m.dn = ldb.Dn(samdb, domain_dn)
                m["msDS-Behavior-Version"]= ldb.MessageElement(
                  str(new_level_domain), ldb.FLAG_MOD_REPLACE,
                            "msDS-Behavior-Version")
                samdb.modify(m)
                # Under partitions
                m = ldb.Message()
                m.dn = ldb.Dn(samdb, "CN=" + lp.get("workgroup")
                  + ",CN=Partitions,%s" % samdb.get_config_basedn())
                m["msDS-Behavior-Version"]= ldb.MessageElement(
                  str(new_level_domain), ldb.FLAG_MOD_REPLACE,
                          "msDS-Behavior-Version")
                try:
                    samdb.modify(m)
                except ldb.LdbError, (enum, emsg):
                    if enum != ldb.ERR_UNWILLING_TO_PERFORM:
                        raise

                level_domain = new_level_domain
                msgs.append("Domain function level changed!")
开发者ID:sprymak,项目名称:samba,代码行数:104,代码来源:domain.py

示例13: UserTests

# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import modify [as 别名]

#.........这里部分代码省略.........
                       '(samaccountname=Administrator)'
        ]
        for expression in expressions:
            t = time.time()
            for i in range(100):
                self.ldb.search(self.ou,
                                expression=expression,
                                scope=SCOPE_SUBTREE,
                                attrs=['cn'])
            print('%d runs %s took %s' % (i, expression,
                                                         time.time() - t), file=sys.stderr)

    def _test_add_many_users(self, n=BATCH_SIZE):
        s = self.state.next_user_id
        e = s + n
        self._add_users(s, e)
        self.state.next_user_id = e

    test_00_00_join_empty_dc = _test_join

    test_00_01_adding_users_1000 = _test_add_many_users
    test_00_02_adding_users_2000 = _test_add_many_users
    test_00_03_adding_users_3000 = _test_add_many_users

    test_00_10_join_unlinked_dc = _test_join
    test_00_11_unindexed_search_3k_users = _test_unindexed_search
    test_00_12_indexed_search_3k_users = _test_indexed_search

    def _link_user_and_group(self, u, g):
        m = Message()
        m.dn = Dn(self.ldb, "CN=g%d,%s" % (g, self.ou_groups))
        m["member"] = MessageElement("cn=u%d,%s" % (u, self.ou_users),
                                     FLAG_MOD_ADD, "member")
        self.ldb.modify(m)

    def _unlink_user_and_group(self, u, g):
        user = "cn=u%d,%s" % (u, self.ou_users)
        group = "CN=g%d,%s" % (g, self.ou_groups)
        m = Message()
        m.dn = Dn(self.ldb, group)
        m["member"] = MessageElement(user, FLAG_MOD_DELETE, "member")
        self.ldb.modify(m)

    def _test_link_many_users(self, n=BATCH_SIZE):
        self._prepare_n_groups(N_GROUPS)
        s = self.state.next_linked_user
        e = s + n
        for i in range(s, e):
            g = i % N_GROUPS
            self._link_user_and_group(i, g)
        self.state.next_linked_user = e

    test_01_01_link_users_1000 = _test_link_many_users
    test_01_02_link_users_2000 = _test_link_many_users
    test_01_03_link_users_3000 = _test_link_many_users

    def _test_link_many_users_offset_1(self, n=BATCH_SIZE):
        s = self.state.next_relinked_user
        e = s + n
        for i in range(s, e):
            g = (i + 1) % N_GROUPS
            self._link_user_and_group(i, g)
        self.state.next_relinked_user = e

    test_02_01_link_users_again_1000 = _test_link_many_users_offset_1
    test_02_02_link_users_again_2000 = _test_link_many_users_offset_1
开发者ID:DavidMulder,项目名称:samba,代码行数:70,代码来源:ad_dc_performance.py

示例14: UserAccountControlTests

# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import modify [as 别名]
class UserAccountControlTests(samba.tests.TestCase):
    def add_computer_ldap(self, computername, others=None, samdb=None):
        if samdb is None:
            samdb = self.samdb
        dn = "CN=%s,OU=test_computer_ou1,%s" % (computername, self.base_dn)
        domainname = ldb.Dn(self.samdb, self.samdb.domain_dn()).canonical_str().replace("/", "")
        samaccountname = "%s$" % computername
        dnshostname = "%s.%s" % (computername, domainname)
        msg_dict = {
            "dn": dn,
            "objectclass": "computer"}
        if others is not None:
            msg_dict = dict(msg_dict.items() + others.items())

        msg = ldb.Message.from_dict(self.samdb, msg_dict )
        msg["sAMAccountName"] = samaccountname

        print "Adding computer account %s" % computername
        samdb.add(msg)

    def get_creds(self, target_username, target_password):
        creds_tmp = Credentials()
        creds_tmp.set_username(target_username)
        creds_tmp.set_password(target_password)
        creds_tmp.set_domain(creds.get_domain())
        creds_tmp.set_realm(creds.get_realm())
        creds_tmp.set_workstation(creds.get_workstation())
        creds_tmp.set_gensec_features(creds_tmp.get_gensec_features()
                                      | gensec.FEATURE_SEAL)
        creds_tmp.set_kerberos_state(DONT_USE_KERBEROS) # kinit is too expensive to use in a tight loop
        return creds_tmp

    def setUp(self):
        super(UserAccountControlTests, self).setUp()
        self.admin_creds = creds
        self.admin_samdb = SamDB(url=ldaphost,
                                 session_info=system_session(),
                                 credentials=self.admin_creds, lp=lp)

        self.unpriv_user = "testuser1"
        self.unpriv_user_pw = "[email protected]"
        self.unpriv_creds = self.get_creds(self.unpriv_user, self.unpriv_user_pw)

        self.admin_samdb.newuser(self.unpriv_user, self.unpriv_user_pw)
        res = self.admin_samdb.search("CN=%s,CN=Users,%s" % (self.unpriv_user, self.admin_samdb.domain_dn()),
                                      scope=SCOPE_BASE,
                                      attrs=["objectSid"])
        self.assertEqual(1, len(res))

        self.unpriv_user_sid = ndr_unpack(security.dom_sid, res[0]["objectSid"][0])
        self.unpriv_user_dn = res[0].dn

        self.samdb = SamDB(url=ldaphost, credentials=self.unpriv_creds, lp=lp)
        self.domain_sid = security.dom_sid(self.samdb.get_domain_sid())
        self.base_dn = self.samdb.domain_dn()

        self.samr = samr.samr("ncacn_ip_tcp:%s[sign]" % host, lp, self.unpriv_creds)
        self.samr_handle = self.samr.Connect2(None, security.SEC_FLAG_MAXIMUM_ALLOWED)
        self.samr_domain = self.samr.OpenDomain(self.samr_handle, security.SEC_FLAG_MAXIMUM_ALLOWED, self.domain_sid)

        self.sd_utils = sd_utils.SDUtils(self.admin_samdb)

        self.admin_samdb.create_ou("OU=test_computer_ou1," + self.base_dn)
        self.unpriv_user_sid = self.sd_utils.get_object_sid(self.unpriv_user_dn)
        mod = "(OA;;CC;bf967a86-0de6-11d0-a285-00aa003049e2;;%s)" % str(self.unpriv_user_sid)

        old_sd = self.sd_utils.read_sd_on_dn("OU=test_computer_ou1," + self.base_dn)

        self.sd_utils.dacl_add_ace("OU=test_computer_ou1," + self.base_dn, mod)

        self.add_computer_ldap("testcomputer-t")

        self.sd_utils.modify_sd_on_dn("OU=test_computer_ou1," + self.base_dn, old_sd)

        self.computernames = ["testcomputer-0"]

        # Get the SD of the template account, then force it to match
        # what we expect for SeMachineAccountPrivilege accounts, so we
        # can confirm we created the accounts correctly
        self.sd_reference_cc = self.sd_utils.read_sd_on_dn("CN=testcomputer-t,OU=test_computer_ou1,%s" % (self.base_dn))

        self.sd_reference_modify = self.sd_utils.read_sd_on_dn("CN=testcomputer-t,OU=test_computer_ou1,%s" % (self.base_dn))
        for ace in self.sd_reference_modify.dacl.aces:
            if ace.type == security.SEC_ACE_TYPE_ACCESS_ALLOWED and ace.trustee == self.unpriv_user_sid:
                ace.access_mask = ace.access_mask | security.SEC_ADS_SELF_WRITE | security.SEC_ADS_WRITE_PROP

        # Now reconnect without domain admin rights
        self.samdb = SamDB(url=ldaphost, credentials=self.unpriv_creds, lp=lp)


    def tearDown(self):
        super(UserAccountControlTests, self).tearDown()
        for computername in self.computernames:
            delete_force(self.admin_samdb, "CN=%s,OU=test_computer_ou1,%s" % (computername, self.base_dn))
        delete_force(self.admin_samdb, "CN=testcomputer-t,OU=test_computer_ou1,%s" % (self.base_dn))
        delete_force(self.admin_samdb, "OU=test_computer_ou1,%s" % (self.base_dn))
        delete_force(self.admin_samdb, "CN=%s,CN=Users,%s" % (self.unpriv_user, self.base_dn))

    def test_add_computer_sd_cc(self):
        user_sid = self.sd_utils.get_object_sid(self.unpriv_user_dn)
#.........这里部分代码省略.........
开发者ID:JiangWeiGitHub,项目名称:Samba,代码行数:103,代码来源:user_account_control.py

示例15: transfer_dns_role

# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import modify [as 别名]
def transfer_dns_role(outf, sambaopts, credopts, role, samdb):
    """Transfer dns FSMO role. """

    if role == "domaindns":
        domain_dn = samdb.domain_dn()
        role_object = "CN=Infrastructure,DC=DomainDnsZones," + domain_dn
    elif role == "forestdns":
        forest_dn = samba.dn_from_dns_name(samdb.forest_dns_name())
        role_object = "CN=Infrastructure,DC=ForestDnsZones," + forest_dn

    try:
        res = samdb.search(role_object,
                           attrs=["fSMORoleOwner"],
                           scope=ldb.SCOPE_BASE,
                           controls=["extended_dn:1:1"])

        if 'fSMORoleOwner' in res[0]:
            try:
                master_guid = str(misc.GUID(ldb.Dn(samdb,
                                  res[0]['fSMORoleOwner'][0])
                                  .get_extended_component('GUID')))
                master_owner = str(ldb.Dn(samdb, res[0]['fSMORoleOwner'][0]))
            except LdbError as e:
                (num, msg) = e.args
                raise CommandError("GUID not found in partition naming master DN %s : %s \n" %
                                   (res[0]['fSMORoleOwner'][0], msg))
    except LdbError as e:
        (num, msg) = e.args
        raise CommandError("DNS partion %s not found : %s" % (role, msg))

    if role == "domaindns":
        master_dns_name = '%s._msdcs.%s' % (master_guid,
                                            samdb.domain_dns_name())
        new_dns_name = '%s._msdcs.%s' % (samdb.get_ntds_GUID(),
                                         samdb.domain_dns_name())
    elif role == "forestdns":
        master_dns_name = '%s._msdcs.%s' % (master_guid,
                                            samdb.forest_dns_name())
        new_dns_name = '%s._msdcs.%s' % (samdb.get_ntds_GUID(),
                                         samdb.forest_dns_name())

    new_owner = samdb.get_dsServiceName()

    if master_dns_name != new_dns_name:
        lp = sambaopts.get_loadparm()
        creds = credopts.get_credentials(lp, fallback_machine=True)
        samdb = SamDB(url="ldap://%s" % (master_dns_name),
                      session_info=system_session(),
                      credentials=creds, lp=lp)

        m = ldb.Message()
        m.dn = ldb.Dn(samdb, role_object)
        m["fSMORoleOwner"] = ldb.MessageElement(master_owner,
                                                ldb.FLAG_MOD_DELETE,
                                                "fSMORoleOwner")

        try:
            samdb.modify(m)
        except LdbError as e:
            (num, msg) = e.args
            raise CommandError("Failed to delete role '%s': %s" %
                               (role, msg))

        m = ldb.Message()
        m.dn = ldb.Dn(samdb, role_object)
        m["fSMORoleOwner"]= ldb.MessageElement(new_owner,
                                               ldb.FLAG_MOD_ADD,
                                               "fSMORoleOwner")
        try:
            samdb.modify(m)
        except LdbError as e:
            (num, msg) = e.args
            raise CommandError("Failed to add role '%s': %s" % (role, msg))

        try:
            connection = samba.drs_utils.drsuapi_connect(samdb.host_dns_name(),
                                                         lp, creds)
        except samba.drs_utils.drsException as e:
            raise CommandError("Drsuapi Connect failed", e)

        try:
            drsuapi_connection = connection[0]
            drsuapi_handle = connection[1]
            req_options = drsuapi.DRSUAPI_DRS_WRIT_REP
            NC = role_object[18:]
            samba.drs_utils.sendDsReplicaSync(drsuapi_connection,
                                              drsuapi_handle,
                                              master_guid,
                                              NC, req_options)
        except samba.drs_utils.drsException as estr:
            raise CommandError("Replication failed", estr)

        outf.write("FSMO transfer of '%s' role successful\n" % role)
        return True
    else:
        outf.write("This DC already has the '%s' FSMO role\n" % role)
        return False
开发者ID:sYnfo,项目名称:samba,代码行数:99,代码来源:fsmo.py


注:本文中的samba.samdb.SamDB.modify方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。