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


Python SamDB.transaction_start方法代码示例

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


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

示例1: modify_schema

# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import transaction_start [as 别名]
def modify_schema(setup_path, names, lp, creds, reporter, ldif, msg):
    """Modify schema using LDIF specified file                                                                                                                                                                          :param setup_path: Path to the setup directory.
    :param names: provision names object.
    :param lp: Loadparm context
    :param creds: Credentials Context
    :param reporter: A progress reporter instance (subclass of AbstractProgressReporter)
    :param ldif: path to the LDIF file
    :param msg: reporter message
    """

    session_info = system_session()

    db = SamDB(url=lp.samdb_url(), session_info=session_info,
               credentials=creds, lp=lp)

    db.transaction_start()

    try:
        reporter.reportNextStep(msg)
        setup_modify_ldif(db, setup_path(ldif), {
                "SCHEMADN": names.schemadn,
                "CONFIGDN": names.configdn
                })
    except:
        db.transaction_cancel()
        raise

    db.transaction_commit()
开发者ID:inverse-inc,项目名称:openchange.old,代码行数:30,代码来源:provision.py

示例2: run

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

        samdb.transaction_start()
        try:
            subnets.delete_subnet(samdb, samdb.get_config_basedn(), subnetname)
            samdb.transaction_commit()
        except subnets.SubnetException, e:
            samdb.transaction_cancel()
            raise CommandError("Error while removing subnet %s, error: %s" % (subnetname, e))
开发者ID:nrensen,项目名称:samba,代码行数:14,代码来源:sites.py

示例3: run

# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import transaction_start [as 别名]
    def run(self, *accounts, **kwargs):
        sambaopts = kwargs.get("sambaopts")
        credopts = kwargs.get("credopts")
        versionpts = kwargs.get("versionopts")
        server = kwargs.get("server")
        accounts_file = kwargs.get("file")

        if server is None:
            raise Exception("You must supply a server")

        if accounts_file is not None:
            accounts = []
            if accounts_file == "-":
                for line in sys.stdin:
                    accounts.append(line.strip())
            else:
                for line in open(accounts_file, 'r'):
                    accounts.append(line.strip())

        lp = sambaopts.get_loadparm()

        creds = credopts.get_credentials(lp, fallback_machine=True)

        # connect to the remote and local SAMs
        samdb = SamDB(url="ldap://%s" % server,
                      session_info=system_session(),
                      credentials=creds, lp=lp)

        local_samdb = SamDB(url=None, session_info=system_session(),
                            credentials=creds, lp=lp)

        destination_dsa_guid = misc.GUID(local_samdb.get_ntds_GUID())

        repl = drs_Replicate("ncacn_ip_tcp:%s[seal,print]" % server, lp, creds,
                             local_samdb, destination_dsa_guid)
        for account in accounts:
            # work out the source and destination GUIDs
            dc_ntds_dn = samdb.get_dsServiceName()
            res = samdb.search(base=dc_ntds_dn, scope=ldb.SCOPE_BASE, attrs=["invocationId"])
            source_dsa_invocation_id = misc.GUID(local_samdb.schema_format_value("objectGUID", res[0]["invocationId"][0]))

            dn = self.get_dn(samdb, account)
            self.outf.write("Replicating DN %s\n" % dn)

            local_samdb.transaction_start()
            try:
                repl.replicate(dn, source_dsa_invocation_id, destination_dsa_guid,
                               exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET, rodc=True)
            except Exception, e:
                local_samdb.transaction_cancel()
                raise CommandError("Error replicating DN %s" % dn, e)
            local_samdb.transaction_commit()
开发者ID:DanilKorotenko,项目名称:samba,代码行数:54,代码来源:rodc.py

示例4: run

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

        samdb.transaction_start()
        try:
            subnets.create_subnet(samdb, samdb.get_config_basedn(), subnetname,
                                  site_of_subnet)
            samdb.transaction_commit()
        except subnets.SubnetException, e:
            samdb.transaction_cancel()
            raise CommandError("Error while creating subnet {0!s}: {1!s}".format(subnetname, e))
开发者ID:runt18,项目名称:samba,代码行数:17,代码来源:sites.py

示例5: run

# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import transaction_start [as 别名]
    def run(self, sitename, sambaopts=None, credopts=None, versionopts=None):
        lp = sambaopts.get_loadparm()
        creds = credopts.get_credentials(lp, fallback_machine=True)
        url =  lp.private_path("sam.ldb")

        if not os.path.exists(url):
            raise CommandError("secret database not found at %s " % url)
        samdb = SamDB(url=url, session_info=system_session(),
            credentials=creds, lp=lp)

        samdb.transaction_start()
        try:
            ok = sites.delete_site(samdb, samdb.get_config_basedn(), sitename)
            samdb.transaction_commit()
        except sites.SiteException, e:
            samdb.transaction_cancel()
            raise CommandError("Error while removing site %s, error: %s" % (sitename, str(e)))
开发者ID:sprymak,项目名称:samba,代码行数:19,代码来源:sites.py

示例6: provision_schema

# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import transaction_start [as 别名]
def provision_schema(setup_path, names, lp, creds, reporter, ldif, msg, modify_mode=False):
    """Provision/modify schema using LDIF specified file
    :param setup_path: Path to the setup directory.
    :param names: provision names object.
    :param lp: Loadparm context
    :param creds: Credentials Context
    :param reporter: A progress reporter instance (subclass of AbstractProgressReporter)
    :param ldif: path to the LDIF file
    :param msg: reporter message
    :param modify_mode: whether entries are added or modified
    """

    session_info = system_session()
    db = SamDB(url=get_ldb_url(lp, creds, names), session_info=session_info,
               credentials=creds, lp=lp)

    db.transaction_start()

    try:
        reporter.reportNextStep(msg)
        if modify_mode:
            ldif_function = setup_modify_ldif
        else:
            ldif_function = setup_add_ldif
        ldif_params = {
            "FIRSTORG": names.firstorg,
            "FIRSTORGDN": names.firstorgdn,
            "FIRSTOU": names.firstou,
            "CONFIGDN": names.configdn,
            "SCHEMADN": names.schemadn,
            "DOMAINDN": names.domaindn,
            "DOMAIN": names.domain,
            "DNSDOMAIN": names.dnsdomain,
            "NETBIOSNAME": names.netbiosname,
            "HOSTNAME": names.hostname
        }
        ldif_function(db, setup_path(ldif), ldif_params)
        setup_modify_ldif(db, setup_path("AD/oc_provision_schema_update.ldif"), ldif_params)
    except:
        db.transaction_cancel()
        raise

    db.transaction_commit()
开发者ID:bradh,项目名称:openchange,代码行数:45,代码来源:provision.py

示例7: run

# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import transaction_start [as 别名]
    def run(self, DN=None, H=None, verbose=False, fix=False, yes=False, cross_ncs=False, quiet=False,
            scope="SUB", credopts=None, sambaopts=None, versionopts=None, attrs=None):

        lp = sambaopts.get_loadparm()
        creds = credopts.get_credentials(lp, fallback_machine=True)

        samdb = SamDB(session_info=system_session(), url=H,
                      credentials=creds, lp=lp)
        if H is None:
            samdb_schema = samdb
        else:
            samdb_schema = SamDB(session_info=system_session(), url=None,
                                 credentials=creds, lp=lp)

        scope_map = { "SUB": ldb.SCOPE_SUBTREE, "BASE":ldb.SCOPE_BASE, "ONE":ldb.SCOPE_ONELEVEL }
        scope = scope.upper()
        if not scope in scope_map:
            raise CommandError("Unknown scope %s" % scope)
        search_scope = scope_map[scope]

        controls = []
        if H.startswith('ldap'):
            controls.append('paged_results:1:1000')
        if cross_ncs:
            controls.append("search_options:1:2")

        if not attrs:
            attrs = ['*']
        else:
            attrs = attrs.split()

        if yes and fix:
            samdb.transaction_start()

        chk = dbcheck(samdb, samdb_schema=samdb_schema, verbose=verbose, fix=fix, yes=yes, quiet=quiet)
        error_count = chk.check_database(DN=DN, scope=search_scope, controls=controls, attrs=attrs)

        if yes and fix:
            samdb.transaction_commit()

        if error_count != 0:
            sys.exit(1)
开发者ID:Arkhont,项目名称:samba,代码行数:44,代码来源:dbcheck.py

示例8: provision_schema

# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import transaction_start [as 别名]
def provision_schema(setup_path, names, lp, creds, reporter, ldif, msg):
    """Provision schema using LDIF specified file
    :param setup_path: Path to the setup directory.
    :param names: provision names object.
    :param lp: Loadparm context
    :param creds: Credentials Context
    :param reporter: A progress reporter instance (subclass of AbstractProgressReporter)
    :param ldif: path to the LDIF file
    :param msg: reporter message
    """

    session_info = system_session()

    db = SamDB(url=lp.samdb_url(), session_info=session_info,
               credentials=creds, lp=lp)

    db.transaction_start()

    try:
        reporter.reportNextStep(msg)
        setup_add_ldif(db, setup_path(ldif), {
                "FIRSTORG": names.firstorg,
                "FIRSTORGDN": names.firstorgdn,
                "CONFIGDN": names.configdn,
                "SCHEMADN": names.schemadn,
                "DOMAINDN": names.domaindn,
                "DOMAIN": names.domain,
                "DNSDOMAIN": names.dnsdomain,
                "NETBIOSNAME": names.netbiosname,
                "HOSTNAME": names.hostname
                })
    except:
        db.transaction_cancel()
        raise

    db.transaction_commit()
开发者ID:inverse-inc,项目名称:openchange.old,代码行数:38,代码来源:provision.py

示例9: deprovision_schema

# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import transaction_start [as 别名]
def deprovision_schema(setup_path, names, lp, creds, reporter, ldif, msg, modify_mode=False):
    """Deprovision/unmodify schema using LDIF specified file, by reverting the
    modifications contained therein.

    :param setup_path: Path to the setup directory.
    :param names: provision names object.
    :param lp: Loadparm context
    :param creds: Credentials Context
    :param reporter: A progress reporter instance (subclass of AbstractProgressReporter)
    :param ldif: path to the LDIF file
    :param msg: reporter message
    :param modify_mode: whether entries are added or modified
    """

    session_info = system_session()
    db = SamDB(url=get_ldb_url(lp, creds, names), session_info=session_info,
               credentials=creds, lp=lp)

    db.transaction_start()

    try:
        reporter.reportNextStep(msg)

        ldif_content = read_and_sub_file(setup_path(ldif),
                                         {"FIRSTORG": names.firstorg,
                                          "FIRSTORGDN": names.firstorgdn,
                                          "CONFIGDN": names.configdn,
                                          "SCHEMADN": names.schemadn,
                                          "DOMAINDN": names.domaindn,
                                          "DOMAIN": names.domain,
                                          "DNSDOMAIN": names.dnsdomain,
                                          "NETBIOSNAME": names.netbiosname,
                                          "HOSTNAME": names.hostname
                                          })
        if modify_mode:
            lines = ldif_content.splitlines()
            keep_line = False
            entries = []
            current_entry = []
            entries.append(current_entry)
            for line in lines:
                skip_this_line = False
                if line.startswith("dn:") or line == "":
                    # current_entry.append("")
                    current_entry = []
                    entries.append(current_entry)
                    keep_line = True
                elif line.startswith("add:"):
                    keep_line = True
                    line = "delete:" + line[4:]
                elif line.startswith("replace:"):
                    keep_line = False
                elif line.startswith("#") or line.strip() == "":
                    skip_this_line = True

                if keep_line and not skip_this_line:
                    current_entry.append(line)

            entries.reverse()
            for entry in entries:
                ldif_content = "\n".join(entry)
                print ldif_content
                try:
                    db.modify_ldif(ldif_content)
                except:
                    pass
        else:
            lines = ldif_content.splitlines()
            lines.reverse()
            for line in lines:
                if line.startswith("dn:"):
                    db.delete(line[4:])

    except:
        db.transaction_cancel()
        raise

    db.transaction_commit()
开发者ID:0x90shell,项目名称:pth-toolkit,代码行数:80,代码来源:provision.py

示例10: DsdbTests

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

#.........这里部分代码省略.........
                                attrs=["dn"])
        self.assertEquals(len(res), 1)
        dn = str(res[0].dn)
        version = self.samdb.get_attribute_replmetadata_version(dn, "description")
        self.samdb.set_attribute_replmetadata_version(dn, "description", version + 2)
        self.assertEqual(self.samdb.get_attribute_replmetadata_version(dn, "description"), version + 2)

    def test_no_error_on_invalid_control(self):
        try:
            res = self.samdb.search(scope=ldb.SCOPE_SUBTREE,
                                    base=self.account_dn,
                                    attrs=["replPropertyMetaData"],
                                    controls=["local_oid:%s:0"
                                              % dsdb.DSDB_CONTROL_INVALID_NOT_IMPLEMENTED])
        except ldb.LdbError as e:
            self.fail("Should have not raised an exception")

    def test_error_on_invalid_critical_control(self):
        try:
            res = self.samdb.search(scope=ldb.SCOPE_SUBTREE,
                                    base=self.account_dn,
                                    attrs=["replPropertyMetaData"],
                                    controls=["local_oid:%s:1"
                                              % dsdb.DSDB_CONTROL_INVALID_NOT_IMPLEMENTED])
        except ldb.LdbError as e:
            (errno, estr) = e.args
            if errno != ldb.ERR_UNSUPPORTED_CRITICAL_EXTENSION:
                self.fail("Got %s should have got ERR_UNSUPPORTED_CRITICAL_EXTENSION"
                          % e[1])

    # Allocate a unique RID for use in the objectSID tests.
    #
    def allocate_rid(self):
        self.samdb.transaction_start()
        try:
            rid = self.samdb.allocate_rid()
        except:
            self.samdb.transaction_cancel()
            raise
        self.samdb.transaction_commit()
        return str(rid)

    # Ensure that duplicate objectSID's are permitted for foreign security
    # principals.
    #
    def test_duplicate_objectSIDs_allowed_on_foreign_security_principals(self):

        #
        # We need to build a foreign security principal SID
        # i.e a  SID not in the current domain.
        #
        dom_sid = self.samdb.get_domain_sid()
        if str(dom_sid).endswith("0"):
            c = "9"
        else:
            c = "0"
        sid_str = str(dom_sid)[:-1] + c + "-1000"
        sid     = ndr_pack(security.dom_sid(sid_str))
        basedn  = self.samdb.get_default_basedn()
        dn      = "CN=%s,CN=ForeignSecurityPrincipals,%s" % (sid_str, basedn)

        #
        # First without control
        #

        try:
开发者ID:Alexander--,项目名称:samba,代码行数:70,代码来源:dsdb.py

示例11: DsdbLockTestCase

# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import transaction_start [as 别名]
class DsdbLockTestCase(SamDBTestCase):
    def test_db_lock1(self):
        basedn = self.samdb.get_default_basedn()
        (r1, w1) = os.pipe()

        pid = os.fork()
        if pid == 0:
            # In the child, close the main DB, re-open just one DB
            del(self.samdb)
            gc.collect()
            self.samdb = SamDB(session_info=self.session,
                               lp=self.lp)

            self.samdb.transaction_start()

            dn = "cn=test_db_lock_user,cn=users," + str(basedn)
            self.samdb.add({
                 "dn": dn,
                 "objectclass": "user",
            })
            self.samdb.delete(dn)

            # Obtain a write lock
            self.samdb.transaction_prepare_commit()
            os.write(w1, b"prepared")
            time.sleep(2)

            # Drop the write lock
            self.samdb.transaction_cancel()
            os._exit(0)

        self.assertEqual(os.read(r1, 8), b"prepared")

        start = time.time()

        # We need to hold this iterator open to hold the all-record lock.
        res = self.samdb.search_iterator()

        # This should take at least 2 seconds because the transaction
        # has a write lock on one backend db open

        # Release the locks
        for l in res:
            pass

        end = time.time()
        self.assertGreater(end - start, 1.9)

        (got_pid, status) = os.waitpid(pid, 0)
        self.assertEqual(got_pid, pid)
        self.assertTrue(os.WIFEXITED(status))
        self.assertEqual(os.WEXITSTATUS(status), 0)

    def test_db_lock2(self):
        basedn = self.samdb.get_default_basedn()
        (r1, w1) = os.pipe()
        (r2, w2) = os.pipe()

        pid = os.fork()
        if pid == 0:
            # In the child, close the main DB, re-open
            del(self.samdb)
            gc.collect()
            self.samdb = SamDB(session_info=self.session,
                               lp=self.lp)

            # We need to hold this iterator open to hold the all-record lock.
            res = self.samdb.search_iterator()

            os.write(w2, b"start")
            if (os.read(r1, 7) != b"started"):
                os._exit(1)

            os.write(w2, b"add")
            if (os.read(r1, 5) != b"added"):
                os._exit(2)

            # Wait 2 seconds to block prepare_commit() in the child.
            os.write(w2, b"prepare")
            time.sleep(2)

            # Release the locks
            for l in res:
                pass

            if (os.read(r1, 8) != b"prepared"):
                os._exit(3)

            os._exit(0)

        # We can start the transaction during the search
        # because both just grab the all-record read lock.
        self.assertEqual(os.read(r2, 5), b"start")
        self.samdb.transaction_start()
        os.write(w1, b"started")

        self.assertEqual(os.read(r2, 3), b"add")
        dn = "cn=test_db_lock_user,cn=users," + str(basedn)
        self.samdb.add({
             "dn": dn,
#.........这里部分代码省略.........
开发者ID:Alexander--,项目名称:samba,代码行数:103,代码来源:dsdb_lock.py

示例12: SiteCoverageTests

# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import transaction_start [as 别名]
class SiteCoverageTests(samba.tests.TestCase):

    def setUp(self):
        self.prefix = "kcc_"
        self.lp = samba.tests.env_loadparm()

        self.sites = {}
        self.site_links = {}

        self.creds = Credentials()
        self.creds.guess(self.lp)
        self.session = system_session()

        self.samdb = SamDB(session_info=self.session,
                           credentials=self.creds,
                           lp=self.lp)

    def tearDown(self):
        self.samdb.transaction_start()

        for site in self.sites:
            delete_force(self.samdb, site, controls=['tree_delete:1'])

        for site_link in self.site_links:
            delete_force(self.samdb, site_link)

        self.samdb.transaction_commit()

    def _add_server(self, name, site):
        dn = "CN={},CN=Servers,{}".format(name, site)
        self.samdb.add({
            "dn": dn,
            "objectClass": "server",
            "serverReference": self.samdb.domain_dn()
        })
        return dn

    def _add_site(self, name):
        dn = "CN={},CN=Sites,{}".format(
            name, self.samdb.get_config_basedn()
        )
        self.samdb.add({
            "dn": dn,
            "objectClass": "site"
        })
        self.samdb.add({
            "dn": "CN=Servers," + dn,
            "objectClass": ["serversContainer"]
        })

        self.sites[dn] = name
        return dn, name.lower()

    def _add_site_link(self, name, links=[], cost=100):
        dn = "CN={},CN=IP,CN=Inter-Site Transports,CN=Sites,{}".format(
            name, self.samdb.get_config_basedn()
        )
        self.samdb.add({
            "dn": dn,
            "objectClass": "siteLink",
            "cost": str(cost),
            "siteList": links
        })
        self.site_links[dn] = name
        return dn

    def test_single_site_link_same_dc_count(self):
        self.samdb.transaction_start()
        site1, name1 = self._add_site(self.prefix + "ABCD")
        site2, name2 = self._add_site(self.prefix + "BCDE")

        uncovered_dn, uncovered = self._add_site(self.prefix + "uncovered")

        self._add_server(self.prefix + "ABCD" + '1', site1)
        self._add_server(self.prefix + "BCDE" + '1', site2)

        self._add_site_link(self.prefix + "link",
                            [site1, site2, uncovered_dn])
        self.samdb.transaction_commit()

        to_cover = uncovered_sites_to_cover(self.samdb, name1)
        to_cover.sort()

        self.assertEqual([uncovered], to_cover)

        to_cover = uncovered_sites_to_cover(self.samdb, name2)
        to_cover.sort()

        self.assertEqual([], to_cover)

    def test_single_site_link_different_dc_count(self):
        self.samdb.transaction_start()
        site1, name1 = self._add_site(self.prefix + "ABCD")
        site2, name2 = self._add_site(self.prefix + "BCDE")

        uncovered_dn, uncovered = self._add_site(self.prefix + "uncovered")

        self._add_server(self.prefix + "ABCD" + '1', site1)
        self._add_server(self.prefix + "ABCD" + '2', site1)
        self._add_server(self.prefix + "BCDE" + '1', site2)
#.........这里部分代码省略.........
开发者ID:Alexander--,项目名称:samba,代码行数:103,代码来源:kcc_utils.py

示例13: Schema

# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import transaction_start [as 别名]
class Schema(object):

    def __init__(self, domain_sid, invocationid=None, schemadn=None,
                 files=None, override_prefixmap=None, additional_prefixmap=None):
        from samba.provision import setup_path

        """Load schema for the SamDB from the AD schema files and
        samba4_schema.ldif

        :param samdb: Load a schema into a SamDB.
        :param schemadn: DN of the schema

        Returns the schema data loaded, to avoid double-parsing when then
        needing to add it to the db
        """

        self.schemadn = schemadn
        # We need to have the am_rodc=False just to keep some warnings quiet -
        # this isn't a real SAM, so it's meaningless.
        self.ldb = SamDB(global_schema=False, am_rodc=False)
        if invocationid is not None:
            self.ldb.set_invocation_id(invocationid)

        self.schema_data = read_ms_schema(
            setup_path('ad-schema/MS-AD_Schema_2K8_R2_Attributes.txt'),
            setup_path('ad-schema/MS-AD_Schema_2K8_R2_Classes.txt'))

        if files is not None:
            for file in files:
                self.schema_data += open(file, 'r').read()

        self.schema_data = substitute_var(self.schema_data,
            {"SCHEMADN": schemadn})
        check_all_substituted(self.schema_data)

        self.schema_dn_modify = read_and_sub_file(
            setup_path("provision_schema_basedn_modify.ldif"),
            {"SCHEMADN": schemadn})

        descr = b64encode(get_schema_descriptor(domain_sid))
        self.schema_dn_add = read_and_sub_file(
            setup_path("provision_schema_basedn.ldif"),
            {"SCHEMADN": schemadn, "DESCRIPTOR": descr})

        if override_prefixmap is not None:
            self.prefixmap_data = override_prefixmap
        else:
            self.prefixmap_data = open(setup_path("prefixMap.txt"), 'r').read()

        if additional_prefixmap is not None:
            for map in additional_prefixmap:
                self.prefixmap_data += "%s\n" % map

        self.prefixmap_data = b64encode(self.prefixmap_data)

        # We don't actually add this ldif, just parse it
        prefixmap_ldif = "dn: %s\nprefixMap:: %s\n\n" % (self.schemadn, self.prefixmap_data)
        self.set_from_ldif(prefixmap_ldif, self.schema_data, self.schemadn)

    def set_from_ldif(self, pf, df, dn):
        dsdb._dsdb_set_schema_from_ldif(self.ldb, pf, df, dn)

    def write_to_tmp_ldb(self, schemadb_path):
        self.ldb.connect(url=schemadb_path)
        self.ldb.transaction_start()
        try:
            self.ldb.add_ldif("""dn: @ATTRIBUTES
linkID: INTEGER

dn: @INDEXLIST
@IDXATTR: linkID
@IDXATTR: attributeSyntax
""")
            # These bits of LDIF are supplied when the Schema object is created
            self.ldb.add_ldif(self.schema_dn_add)
            self.ldb.modify_ldif(self.schema_dn_modify)
            self.ldb.add_ldif(self.schema_data)
        except:
            self.ldb.transaction_cancel()
            raise
        else:
            self.ldb.transaction_commit()

    # Return a hash with the forward attribute as a key and the back as the
    # value
    def linked_attributes(self):
        return get_linked_attributes(self.schemadn, self.ldb)

    def dnsyntax_attributes(self):
        return get_dnsyntax_attributes(self.schemadn, self.ldb)

    def convert_to_openldap(self, target, mapping):
        return dsdb._dsdb_convert_schema_to_openldap(self.ldb, target, mapping)
开发者ID:sprymak,项目名称:samba,代码行数:95,代码来源:schema.py

示例14: Schema

# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import transaction_start [as 别名]
class Schema(object):

    # the schema files (and corresponding object version) that we know about
    base_schemas = {
       "2008_R2_old" : ("MS-AD_Schema_2K8_R2_Attributes.txt",
                        "MS-AD_Schema_2K8_R2_Classes.txt",
                        47),
       "2008_R2" : ("Attributes_for_AD_DS__Windows_Server_2008_R2.ldf",
                    "Classes_for_AD_DS__Windows_Server_2008_R2.ldf",
                    47),
       "2012"    : ("AD_DS_Attributes__Windows_Server_2012.ldf",
                    "AD_DS_Classes__Windows_Server_2012.ldf",
                    56),
       "2012_R2" : ("AD_DS_Attributes__Windows_Server_2012_R2.ldf",
                    "AD_DS_Classes__Windows_Server_2012_R2.ldf",
                    69),
    }

    def __init__(self, domain_sid, invocationid=None, schemadn=None,
                 files=None, override_prefixmap=None, additional_prefixmap=None,
                 base_schema=None):
        from samba.provision import setup_path

        """Load schema for the SamDB from the AD schema files and
        samba4_schema.ldif

        :param samdb: Load a schema into a SamDB.
        :param schemadn: DN of the schema

        Returns the schema data loaded, to avoid double-parsing when then
        needing to add it to the db
        """

        if base_schema is None:
            base_schema = Schema.default_base_schema()

        self.base_schema = base_schema

        self.schemadn = schemadn
        # We need to have the am_rodc=False just to keep some warnings quiet -
        # this isn't a real SAM, so it's meaningless.
        self.ldb = SamDB(global_schema=False, am_rodc=False)
        if invocationid is not None:
            self.ldb.set_invocation_id(invocationid)

        self.schema_data = read_ms_schema(
            setup_path('ad-schema/%s' % Schema.base_schemas[base_schema][0]),
            setup_path('ad-schema/%s' % Schema.base_schemas[base_schema][1]))

        if files is not None:
            for file in files:
                self.schema_data += open(file, 'r').read()

        self.schema_data = substitute_var(self.schema_data,
            {"SCHEMADN": schemadn})
        check_all_substituted(self.schema_data)

        schema_version = str(Schema.get_version(base_schema))
        self.schema_dn_modify = read_and_sub_file(
            setup_path("provision_schema_basedn_modify.ldif"),
            {"SCHEMADN": schemadn, "OBJVERSION" : schema_version})

        descr = b64encode(get_schema_descriptor(domain_sid)).decode('utf8')
        self.schema_dn_add = read_and_sub_file(
            setup_path("provision_schema_basedn.ldif"),
            {"SCHEMADN": schemadn, "DESCRIPTOR": descr})

        if override_prefixmap is not None:
            self.prefixmap_data = override_prefixmap
        else:
            self.prefixmap_data = open(setup_path("prefixMap.txt"), 'r').read()

        if additional_prefixmap is not None:
            for map in additional_prefixmap:
                self.prefixmap_data += "%s\n" % map

        self.prefixmap_data = b64encode(self.prefixmap_data).decode('utf8')

        # We don't actually add this ldif, just parse it
        prefixmap_ldif = "dn: %s\nprefixMap:: %s\n\n" % (self.schemadn, self.prefixmap_data)
        self.set_from_ldif(prefixmap_ldif, self.schema_data, self.schemadn)

    @staticmethod
    def default_base_schema():
        """Returns the default base schema to use"""
        return "2008_R2"

    @staticmethod
    def get_version(base_schema):
        """Returns the base schema's object version, e.g. 47 for 2008_R2"""
        return Schema.base_schemas[base_schema][2]

    def set_from_ldif(self, pf, df, dn):
        dsdb._dsdb_set_schema_from_ldif(self.ldb, pf, df, dn)

    def write_to_tmp_ldb(self, schemadb_path):
        self.ldb.connect(url=schemadb_path)
        self.ldb.transaction_start()
        try:
            # These are actually ignored, as the schema has been forced
#.........这里部分代码省略.........
开发者ID:Alexander--,项目名称:samba,代码行数:103,代码来源:schema.py

示例15: run

# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import transaction_start [as 别名]
    def run(self, DN=None, H=None, verbose=False, fix=False, yes=False,
            cross_ncs=False, quiet=False,
            scope="SUB", credopts=None, sambaopts=None, versionopts=None,
            attrs=None, reindex=False, force_modules=False,
            reset_well_known_acls=False):

        lp = sambaopts.get_loadparm()

        over_ldap = H is not None and H.startswith('ldap')

        if over_ldap:
            creds = credopts.get_credentials(lp, fallback_machine=True)
        else:
            creds = None

        if force_modules:
            samdb = SamDB(session_info=system_session(), url=H,
                          credentials=creds, lp=lp, options=["modules=samba_dsdb"])
        else:
            try:
                samdb = SamDB(session_info=system_session(), url=H,
                              credentials=creds, lp=lp)
            except:
                raise CommandError("Failed to connect to DB at %s.  If this is a really old sam.ldb (before alpha9), then try again with --force-modules" % H)


        if H is None or not over_ldap:
            samdb_schema = samdb
        else:
            samdb_schema = SamDB(session_info=system_session(), url=None,
                                 credentials=creds, lp=lp)

        scope_map = { "SUB": ldb.SCOPE_SUBTREE, "BASE": ldb.SCOPE_BASE, "ONE":ldb.SCOPE_ONELEVEL }
        scope = scope.upper()
        if not scope in scope_map:
            raise CommandError("Unknown scope %s" % scope)
        search_scope = scope_map[scope]

        controls = ['show_deleted:1']
        if over_ldap:
            controls.append('paged_results:1:1000')
        if cross_ncs:
            controls.append("search_options:1:2")

        if not attrs:
            attrs = ['*']
        else:
            attrs = attrs.split()

        started_transaction = False
        if yes and fix:
            samdb.transaction_start()
            started_transaction = True
        try:
            chk = dbcheck(samdb, samdb_schema=samdb_schema, verbose=verbose,
                          fix=fix, yes=yes, quiet=quiet, in_transaction=started_transaction,
                          reset_well_known_acls=reset_well_known_acls)

            if reindex:
                self.outf.write("Re-indexing...\n")
                error_count = 0
                if chk.reindex_database():
                    self.outf.write("completed re-index OK\n")

            elif force_modules:
                self.outf.write("Resetting @MODULES...\n")
                error_count = 0
                if chk.reset_modules():
                    self.outf.write("completed @MODULES reset OK\n")

            else:
                error_count = chk.check_database(DN=DN, scope=search_scope,
                        controls=controls, attrs=attrs)
        except:
            if started_transaction:
                samdb.transaction_cancel()
            raise

        if started_transaction:
            samdb.transaction_commit()

        if error_count != 0:
            sys.exit(1)
开发者ID:AIdrifter,项目名称:samba,代码行数:85,代码来源:dbcheck.py


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