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


Python SamDB.search方法代码示例

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


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

示例1: run

# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import search [as 别名]
    def run(self, attribute, 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)

        schema_dn = samdb.schema_dn()

        may_filt = '(&(objectClass=classSchema)' \
         '(|(mayContain={0})(systemMayContain={0})))'.format(attribute)
        must_filt = '(&(objectClass=classSchema)' \
         '(|(mustContain={0})(systemMustContain={0})))'.format(attribute)

        may_res = samdb.search(base=schema_dn, scope=ldb.SCOPE_SUBTREE,
                           expression=may_filt, attrs=['cn'])
        must_res = samdb.search(base=schema_dn, scope=ldb.SCOPE_SUBTREE,
                           expression=must_filt, attrs=['cn'])

        self.outf.write('--- MAY contain ---\n')
        for msg in may_res:
            self.outf.write('%s\n' % msg['cn'][0])

        self.outf.write('--- MUST contain ---\n')
        for msg in must_res:
            self.outf.write('%s\n' % msg['cn'][0])
开发者ID:Alexander--,项目名称:samba,代码行数:28,代码来源:schema.py

示例2: SchemaTests_msDS_isRODC

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

    def setUp(self):
        super(SchemaTests_msDS_isRODC, self).setUp()
        self.ldb =  SamDB(host, credentials=creds,
            session_info=system_session(lp), lp=lp, options=ldb_options)
        res = self.ldb.search(base="", expression="", scope=SCOPE_BASE, attrs=["defaultNamingContext"])
        self.assertEquals(len(res), 1)
        self.base_dn = res[0]["defaultNamingContext"][0]

    def test_objectClass_ntdsdsa(self):
        res = self.ldb.search(self.base_dn, expression="objectClass=nTDSDSA",
                              attrs=["msDS-isRODC"], controls=["search_options:1:2"])
        for ldb_msg in res:
            self.assertTrue("msDS-isRODC" in ldb_msg)

    def test_objectClass_server(self):
        res = self.ldb.search(self.base_dn, expression="objectClass=server",
                              attrs=["msDS-isRODC"], controls=["search_options:1:2"])
        for ldb_msg in res:
            ntds_search_dn = "CN=NTDS Settings,%s" % ldb_msg['dn']
            try:
                res_check = self.ldb.search(ntds_search_dn, attrs=["objectCategory"])
            except LdbError, (num, _):
                self.assertEquals(num, ERR_NO_SUCH_OBJECT)
                print("Server entry %s doesn't have a NTDS settings object" % res[0]['dn'])
            else:
                self.assertTrue("objectCategory" in res_check[0])
                self.assertTrue("msDS-isRODC" in ldb_msg)
开发者ID:GuillaumeGomez,项目名称:samba,代码行数:31,代码来源:ldap_schema.py

示例3: test_1000_binds

# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import search [as 别名]
    def test_1000_binds(self):

        for x in range(1, 1000):
            samdb = SamDB(host, credentials=creds,
                         session_info=system_session(self.lp), lp=self.lp)
            samdb.search(base=samdb.domain_dn(),
                         scope=SCOPE_BASE, attrs=["*"])
开发者ID:DavidMulder,项目名称:samba,代码行数:9,代码来源:ad_dc_multi_bind.py

示例4: BaseDeleteTests

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

    def GUID_string(self, guid):
        return self.ldb.schema_format_value("objectGUID", guid)

    def setUp(self):
        super(BaseDeleteTests, self).setUp()
        self.ldb = SamDB(host, credentials=creds, session_info=system_session(lp), lp=lp)

        self.base_dn = self.ldb.domain_dn()
        self.configuration_dn = self.ldb.get_config_basedn().get_linearized()

    def search_guid(self, guid):
        print "SEARCH by GUID {0!s}".format(self.GUID_string(guid))

        res = self.ldb.search(base="<GUID={0!s}>".format(self.GUID_string(guid)),
                         scope=SCOPE_BASE, controls=["show_deleted:1"])
        self.assertEquals(len(res), 1)
        return res[0]

    def search_dn(self,dn):
        print "SEARCH by DN {0!s}".format(dn)

        res = self.ldb.search(expression="(objectClass=*)",
                         base=dn,
                         scope=SCOPE_BASE,
                         controls=["show_deleted:1"])
        self.assertEquals(len(res), 1)
        return res[0]
开发者ID:runt18,项目名称:samba,代码行数:31,代码来源:deletetest.py

示例5: test_join_time_ridalloc

# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import search [as 别名]
    def test_join_time_ridalloc(self):
        """Perform a join against the RID manager and assert we have a 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_owner['dns_name'], "RIDALLOCTEST5")
        try:
            # Connect to the database
            ldb_url = "tdb://%s" % os.path.join(targetdir, "private/sam.ldb")
            smbconf = os.path.join(targetdir, "etc/smb.conf")

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

            # 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])

            # 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_owner['dns_name'], "RIDALLOCTEST5")
            shutil.rmtree(targetdir, ignore_errors=True)
开发者ID:samba-team,项目名称:samba,代码行数:32,代码来源:ridalloc_exop.py

示例6: test_multiple_searches

# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import search [as 别名]
    def test_multiple_searches(self):
        """The maximum number of concurrent vlv searches per connection is
        currently set at 3. That means if you open 4 VLV searches the
        cookie on the first one should fail.
        """
        # Windows has a limit of 10 VLVs where there are low numbers
        # of objects in each search.
        attrs = ([x for x in self.users[0].keys() if x not in
                  ('dn', 'objectclass')] * 2)[:12]

        vlv_cookies = []
        for attr in attrs:
            sort_control = "server_sort:1:0:%s" % attr

            res = self.ldb.search(self.ou,
                                  scope=ldb.SCOPE_ONELEVEL,
                                  attrs=[attr],
                                  controls=[sort_control,
                                            "vlv:1:1:1:1:0"])

            cookie = get_cookie(res.controls, len(self.users))
            vlv_cookies.append(cookie)
            time.sleep(0.2)

        # now this one should fail
        self.assertRaises(ldb.LdbError,
                          self.ldb.search,
                          self.ou,
                          scope=ldb.SCOPE_ONELEVEL,
                          attrs=[attr],
                          controls=[sort_control,
                                    "vlv:1:1:1:1:0:%s" % vlv_cookies[0]])

        # and this one should succeed
        res = self.ldb.search(self.ou,
                              scope=ldb.SCOPE_ONELEVEL,
                              attrs=[attr],
                              controls=[sort_control,
                                        "vlv:1:1:1:1:0:%s" % vlv_cookies[-1]])

        # this one should fail because it is a new connection and
        # doesn't share cookies
        new_ldb = SamDB(host, credentials=creds,
                        session_info=system_session(lp), lp=lp)

        self.assertRaises(ldb.LdbError,
                          new_ldb.search, self.ou,
                          scope=ldb.SCOPE_ONELEVEL,
                          attrs=[attr],
                          controls=[sort_control,
                                    "vlv:1:1:1:1:0:%s" % vlv_cookies[-1]])

        # but now without the critical flag it just does no VLV.
        new_ldb.search(self.ou,
                       scope=ldb.SCOPE_ONELEVEL,
                       attrs=[attr],
                       controls=[sort_control,
                                 "vlv:0:1:1:1:0:%s" % vlv_cookies[-1]])
开发者ID:DavidMulder,项目名称:samba,代码行数:60,代码来源:vlv.py

示例7: SambaOCHelper

# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import search [as 别名]
class SambaOCHelper(object):
    def __init__(self):
        self.samba_lp = LoadParm()
        self.samba_lp.set('debug level', '0')
        self.samba_lp.load_default()
        url = self.samba_lp.get('dcerpc_mapiproxy:samdb_url') or \
            self.samba_lp.private_path("sam.ldb")
        self.samdb = SamDB(url=url,
                           lp=self.samba_lp,
                           session_info=system_session())
        self.conn = self._open_mysql_connection()

    def _open_mysql_connection(self):
        connection_string = self.samba_lp.get('mapiproxy:openchangedb')
        if not connection_string:
            raise Exception("Not found mapiproxy:openchangedb on samba configuration")
        # mysql://openchange:[email protected]/openchange
        m = re.search(r'(?P<scheme>.+)://(?P<user>.+):(?P<pass>.+)@(?P<host>.+)/(?P<db>.+)',
                      connection_string)
        if not m:
            raise Exception("Unable to parse mapiproxy:openchangedb: %s" %
                            connection_string)
        group_dict = m.groupdict()
        if group_dict['scheme'] != 'mysql':
            raise Exception("mapiproxy:openchangedb should start with mysql:// (we got %s)",
                            group_dict['scheme'])

        conn = MySQLdb.connect(host=group_dict['host'], user=group_dict['user'],
                               passwd=group_dict['pass'], db=group_dict['db'])
        conn.autocommit(True)
        return conn

    def invalid_user(self, username):
        ret = self.samdb.search(base=self.samdb.domain_dn(),
                                scope=ldb.SCOPE_SUBTREE,
                                expression="(sAMAccountName=%s)" % ldb.binary_encode(username))
        return len(ret) != 1

    def find_email_of(self, username):
        ret = self.samdb.search(base=self.samdb.domain_dn(),
                                scope=ldb.SCOPE_SUBTREE, attrs=["mail"],
                                expression="(sAMAccountName=%s)" % ldb.binary_encode(username))
        return ret[0]["mail"][0]

    def active_openchange_users(self):
        c = self.conn.cursor()
        c.execute("SELECT name FROM mailboxes")
        return sorted([row[0] for row in c.fetchall()])

    def get_indexing_cache(self):
        memcached_server = self.samba_lp.get('mapistore:indexing_cache')
        if not memcached_server:
            return "127.0.0.1:11211"
        # This should has a format like: --SERVER=11.22.33.44:11211
        return memcached_server.split('=')[1]
开发者ID:blaxter,项目名称:openchange,代码行数:57,代码来源:openchange_user_cleanup.py

示例8: deprovision

# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import search [as 别名]
def deprovision(setup_path, lp, creds, firstorg=None, firstou=None, reporter=None):
    """Remove all configuration entries added by the OpenChange
    installation.

    :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)
    """
    if reporter is None:
        reporter = TextProgressReporter()

    session_info = system_session()

    lp.set("dsdb:schema update allowed", "yes")

    names = guess_names_from_smbconf(lp, None, None)

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

    try:
        config_dn = samdb.get_config_basedn()
        ret = samdb.search(base=config_dn, scope=ldb.SCOPE_SUBTREE, expression="(objectClass=msExchExchangeServer)")
        if len(ret) > 1:
            # If we are the primary folder store server, raise exception
            # The user has to set another server as primary before unregister
            # this one
            our_siteFolderName = "CN=Public Folder Store (%s),CN=First Storage Group,CN=InformationStore,CN=%s,CN=Servers,CN=First Administrative Group,CN=Administrative Groups,%s" % (names.netbiosname, names.netbiosname, names.firstorgdn)
            dn = "CN=First Administrative Group,CN=Administrative Groups,%s" % names.firstorgdn
            ret = samdb.search(base=dn, scope=ldb.SCOPE_BASE, attrs=['siteFolderServer'])
            assert len(ret) == 1
            siteFolderName = ret[0]["siteFolderServer"][0]
            if our_siteFolderName.lower() == siteFolderName.lower():
                raise Exception("This server is the primary folder store server")

            # If we are the primary receipt update service, raise exception
            our_addressListServiceLink = "CN=%s,CN=Servers,CN=First Administrative Group,CN=Administrative Groups,%s" % (names.netbiosname, names.firstorgdn)
            dn = "CN=Recipient Update Service (%s),CN=Recipient Update Services,CN=Address Lists Container,%s" % (names.domain, names.firstorgdn)
            ret = samdb.search(base=dn, scope=ldb.SCOPE_BASE, attrs=['msExchAddressListServiceLink'])
            assert len(ret) == 1
            addressListServiceLink = ret[0]['msExchAddressListServiceLink'][0]
            if our_addressListServiceLink.lower() == addressListServiceLink.lower():
                raise Exception("This server is the primary receipt update service server")

            # Unregister the server
            deprovision_schema(setup_path, names, lp, creds, reporter, "AD/oc_provision_configuration_new_server.ldif", "Remove Exchange samba registration")
        else:
            # This is the unique server, remove full schema
            deprovision_schema(setup_path, names, lp, creds, reporter, "AD/oc_provision_configuration.ldif", "Remove Exchange configuration objects")
    except LdbError, ldb_error:
        print ("[!] error while deprovisioning the Exchange configuration"
               " objects (%d): %s" % ldb_error.args)
开发者ID:spclops,项目名称:openchange,代码行数:56,代码来源:provision.py

示例9: test_offline_manual_seized_ridalloc_with_dbcheck

# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import search [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

示例10: test_offline_manual_seized_ridalloc_add_user_as_admin

# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import search [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

示例11: SambaOCHelper

# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import search [as 别名]
class SambaOCHelper(object):
    def __init__(self):
        self.samba_lp = LoadParm()
        self.samba_lp.set("debug level", "0")
        self.samba_lp.load_default()
        url = self.samba_lp.get("dcerpc_mapiproxy:samdb_url") or self.samba_lp.private_path("sam.ldb")
        self.samdb = SamDB(url=url, lp=self.samba_lp, session_info=system_session())
        self.conn = self._open_mysql_connection()

    def _open_mysql_connection(self):
        connection_string = self.samba_lp.get("mapiproxy:openchangedb")
        if not connection_string:
            raise Exception("Not found mapiproxy:openchangedb on samba configuration")
        # mysql://openchange:[email protected]/openchange
        m = re.search(r"(?P<scheme>.+)://(?P<user>.+):(?P<pass>.+)@(?P<host>.+)/(?P<db>.+)", connection_string)
        if not m:
            raise Exception("Unable to parse mapiproxy:openchangedb: %s" % connection_string)
        group_dict = m.groupdict()
        if group_dict["scheme"] != "mysql":
            raise Exception("mapiproxy:openchangedb should start with mysql:// (we got %s)", group_dict["scheme"])

        conn = MySQLdb.connect(
            host=group_dict["host"], user=group_dict["user"], passwd=group_dict["pass"], db=group_dict["db"]
        )
        conn.autocommit(True)
        return conn

    def invalid_user(self, username):
        ret = self.samdb.search(
            base=self.samdb.domain_dn(),
            scope=ldb.SCOPE_SUBTREE,
            expression="(sAMAccountName=%s)" % ldb.binary_encode(username),
        )
        return len(ret) != 1

    def find_email_of(self, username):
        ret = self.samdb.search(
            base=self.samdb.domain_dn(),
            scope=ldb.SCOPE_SUBTREE,
            attrs=["mail"],
            expression="(sAMAccountName=%s)" % ldb.binary_encode(username),
        )
        return ret[0]["mail"][0]

    def active_openchange_users(self):
        c = self.conn.cursor()
        c.execute("SELECT name FROM mailboxes")
        return sorted([row[0] for row in c.fetchall()])
开发者ID:wewela,项目名称:openchange,代码行数:50,代码来源:openchange_user_cleanup.py

示例12: run

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

        lp = sambaopts.get_loadparm()
        creds = credopts.get_credentials(lp, fallback_machine=True)
        samdb = SamDB(url=H, session_info=system_session(),
                      credentials=creds, lp=lp)

        attrs = None
        if group_attrs:
            attrs = group_attrs.split(",")

        filter = ("(&(sAMAccountType=%d)(sAMAccountName=%s))" %
                     ( ATYPE_SECURITY_GLOBAL_GROUP,
                       ldb.binary_encode(groupname)))

        domaindn = samdb.domain_dn()

        try:
            res = samdb.search(base=domaindn, expression=filter,
                               scope=ldb.SCOPE_SUBTREE, attrs=attrs)
            user_dn = res[0].dn
        except IndexError:
            raise CommandError('Unable to find group "%s"' % (groupname))

        for msg in res:
            user_ldif = samdb.write_ldif(msg, ldb.CHANGETYPE_NONE)
            self.outf.write(user_ldif)
开发者ID:Alexander--,项目名称:samba,代码行数:30,代码来源:group.py

示例13: run

# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import search [as 别名]
    def run(self, 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)

        res = samdb.search(pso_container(samdb), scope=ldb.SCOPE_SUBTREE,
                           attrs=['name', 'msDS-PasswordSettingsPrecedence'],
                           expression="(objectClass=msDS-PasswordSettings)")

        # an unprivileged search against Windows returns nothing here. On Samba
        # we get the PSO names, but not their attributes
        if len(res) == 0 or 'msDS-PasswordSettingsPrecedence' not in res[0]:
            self.outf.write("No PSOs are present, or you don't have permission to view them.\n")
            return

        # sort the PSOs so they're displayed in order of precedence
        pso_list = sorted(res, cmp=pso_cmp)

        self.outf.write("Precedence | PSO name\n")
        self.outf.write("--------------------------------------------------\n")

        for pso in pso_list:
            precedence = pso['msDS-PasswordSettingsPrecedence']
            self.outf.write("%-10s | %s\n" %(precedence, pso['name']))
开发者ID:Alexander--,项目名称:samba,代码行数:28,代码来源:pso.py

示例14: run

# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import search [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

示例15: run

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

        lp = sambaopts.get_loadparm()
        creds = credopts.get_credentials(lp, fallback_machine=True)
        samdb = SamDB(url=H, session_info=system_session(),
                      credentials=creds, lp=lp)

        attrs = None
        if computer_attrs:
            attrs = computer_attrs.split(",")

        samaccountname = computername
        if not computername.endswith('$'):
            samaccountname = "%s$" % computername

        filter = ("(&(sAMAccountType=%d)(sAMAccountName=%s))" %
                  (dsdb.ATYPE_WORKSTATION_TRUST,
                   ldb.binary_encode(samaccountname)))

        domaindn = samdb.domain_dn()

        try:
            res = samdb.search(base=domaindn, expression=filter,
                               scope=ldb.SCOPE_SUBTREE, attrs=attrs)
            computer_dn = res[0].dn
        except IndexError:
            raise CommandError('Unable to find computer "%s"' %
                               samaccountname)

        for msg in res:
            computer_ldif = samdb.write_ldif(msg, ldb.CHANGETYPE_NONE)
            self.outf.write(computer_ldif)
开发者ID:Alexander--,项目名称:samba,代码行数:35,代码来源:computer.py


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