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


Python Ldb.search方法代码示例

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


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

示例1: init

# 需要导入模块: from samba import Ldb [as 别名]
# 或者: from samba.Ldb import search [as 别名]
    def init(self):
        # Check to see that this 'existing' LDAP backend in fact exists
        ldapi_db = Ldb(self.ldapi_uri)
        ldapi_db.search(base="", scope=SCOPE_BASE,
            expression="(objectClass=OpenLDAProotDSE)")

        # For now, assume existing backends at least emulate OpenLDAP
        self.ldap_backend_type = "openldap"
开发者ID:Alexander--,项目名称:samba,代码行数:10,代码来源:backend.py

示例2: start

# 需要导入模块: from samba import Ldb [as 别名]
# 或者: from samba.Ldb import search [as 别名]
    def start(self):
        from samba.provision import ProvisioningError
        self.slapd_command_escaped = "\'" + "\' \'".join(
            self.slapd_command) + "\'"
        ldap_backend_script = os.path.join(self.ldapdir,
                                           "ldap_backend_startup.sh")
        f = open(ldap_backend_script, 'w')
        try:
            f.write("#!/bin/sh\n" + self.slapd_command_escaped + " [email protected]\n")
        finally:
            f.close()

        os.chmod(ldap_backend_script, 0o755)

        # Now start the slapd, so we can provision onto it.  We keep the
        # subprocess context around, to kill this off at the successful
        # end of the script
        self.slapd = subprocess.Popen(
            self.slapd_provision_command, close_fds=True, shell=False)

        count = 0
        while self.slapd.poll() is None:
            # Wait until the socket appears
            try:
                time.sleep(1)
                ldapi_db = Ldb(
                    self.ldap_uri, lp=self.lp, credentials=self.credentials)
                ldapi_db.search(
                    base="",
                    scope=SCOPE_BASE,
                    expression="(objectClass=OpenLDAProotDSE)")
                # If we have got here, then we must have a valid connection to
                # the LDAP server!
                return
            except LdbError:
                count = count + 1

                if count > 15:
                    self.logger.error(
                        "Could not connect to slapd started with: %s" % "\'" +
                        "\' \'".join(self.slapd_provision_command) + "\'")
                    raise ProvisioningError(
                        "slapd never accepted a connection within 15 seconds of starting"
                    )

        self.logger.error("Could not start slapd with: %s" % "\'" +
                          "\' \'".join(self.slapd_provision_command) + "\'")
        raise ProvisioningError(
            "slapd died before we could make a connection to it")
开发者ID:sYnfo,项目名称:samba,代码行数:51,代码来源:backend.py

示例3: autenticacion

# 需要导入模块: from samba import Ldb [as 别名]
# 或者: from samba.Ldb import search [as 别名]
def autenticacion(creds, lp):
    """
    Cumple con la idea de inyección, así que debería ser testeable
    """
    try:
        ldap_conn = Ldb('ldap://localhost', lp=lp, credentials=creds)
        
        domain_dn = ldap_conn.get_default_basedn()
        search_filter='sAMAccountName={0}'.format(creds.get_username())
       
        # NOTA: No intentes usar searchone para este caso específico. Dn resulta ser una clase no iterable
        busqueda = ldap_conn.search(base=domain_dn, scope=SCOPE_SUBTREE, expression=search_filter, attrs=['dn', 'memberOf', 'displayName'])
        user_dn = busqueda[0].dn
       
        sesion = user_session(ldap_conn, lp_ctx=lp, dn=user_dn, session_info_flags=session_info_flags)

        # Este punto podría ser importante para la idea de login
        token = sesion.security_token

    except LdbError as e:
        log.warning("Error LDB: %s" % e)
        return False;
    except IndexError as e:
        log.warning("El usuario %s no existe" % creds.get_username())
        return False;
    except Exception as e:
        log.warning("Error no contemplado %s " % e)
        return False;
   
    return busqueda
开发者ID:VTacius,项目名称:justine,代码行数:32,代码来源:conexion.py

示例4: delta_update_basesamdb

# 需要导入模块: from samba import Ldb [as 别名]
# 或者: from samba.Ldb import search [as 别名]
def delta_update_basesamdb(refsampath, sampath, creds, session, lp, message):
    """Update the provision container db: sam.ldb
    This function is aimed for alpha9 and newer;

    :param refsampath: Path to the samdb in the reference provision
    :param sampath: Path to the samdb in the upgraded provision
    :param creds: Credential used for openning LDB files
    :param session: Session to use for openning LDB files
    :param lp: A loadparam object
    :return: A msg_diff object with the difference between the @ATTRIBUTES
             of the current provision and the reference provision
    """

    message(SIMPLE,
            "Update base samdb by searching difference with reference one")
    refsam = Ldb(refsampath, session_info=session, credentials=creds,
                    lp=lp, options=["modules:"])
    sam = Ldb(sampath, session_info=session, credentials=creds, lp=lp,
                options=["modules:"])

    empty = ldb.Message()
    deltaattr = None
    reference = refsam.search(expression="")

    for refentry in reference:
        entry = sam.search(expression="distinguishedName=%s" % refentry["dn"],
                            scope=SCOPE_SUBTREE)
        if not len(entry):
            delta = sam.msg_diff(empty, refentry)
            message(CHANGE, "Adding %s to sam db" % str(refentry.dn))
            if str(refentry.dn) == "@PROVISION" and\
                delta.get(samba.provision.LAST_PROVISION_USN_ATTRIBUTE):
                delta.remove(samba.provision.LAST_PROVISION_USN_ATTRIBUTE)
            delta.dn = refentry.dn
            sam.add(delta)
        else:
            delta = sam.msg_diff(entry[0], refentry)
            if str(refentry.dn) == "@ATTRIBUTES":
                deltaattr = sam.msg_diff(refentry, entry[0])
            if str(refentry.dn) == "@PROVISION" and\
                delta.get(samba.provision.LAST_PROVISION_USN_ATTRIBUTE):
                delta.remove(samba.provision.LAST_PROVISION_USN_ATTRIBUTE)
            if len(delta.items()) > 1:
                delta.dn = refentry.dn
                sam.modify(delta)

    return deltaattr
开发者ID:DanilKorotenko,项目名称:samba,代码行数:49,代码来源:upgradehelpers.py

示例5: newuser

# 需要导入模块: from samba import Ldb [as 别名]
# 或者: from samba.Ldb import search [as 别名]
def newuser(lp, creds, username=None):
    """extend user record with OpenChange settings.
    
    :param lp: Loadparm context
    :param creds: Credentials context
    :param username: Name of user to extend
    """

    names = guess_names_from_smbconf(lp, None, None)
    db = Ldb(url=get_ldb_url(lp, creds, names), session_info=system_session(), 
             credentials=creds, lp=lp)
    user_dn = get_user_dn(db, "CN=Users,%s" % names.domaindn, username)
    if user_dn:
        extended_user = """
dn: %(user_dn)s
changetype: modify
add: mailNickName
mailNickname: %(username)s
add: homeMDB
homeMDB: CN=Mailbox Store (%(netbiosname)s),CN=First Storage Group,CN=InformationStore,CN=%(netbiosname)s,CN=Servers,CN=First Administrative Group,CN=Administrative Groups,CN=%(firstorg)s,CN=Microsoft Exchange,CN=Services,CN=Configuration,%(domaindn)s
add: homeMTA
homeMTA: CN=Mailbox Store (%(netbiosname)s),CN=First Storage Group,CN=InformationStore,CN=%(netbiosname)s,CN=Servers,CN=First Administrative Group,CN=Administrative Groups,CN=%(firstorg)s,CN=Microsoft Exchange,CN=Services,CN=Configuration,%(domaindn)s
add: legacyExchangeDN
legacyExchangeDN: /o=%(firstorg)s/ou=First Administrative Group/cn=Recipients/cn=%(username)s
add: proxyAddresses
proxyAddresses: =EX:/o=%(firstorg)s/ou=First Administrative Group/cn=Recipients/cn=%(username)s
proxyAddresses: smtp:[email protected]%(dnsdomain)s
proxyAddresses: X400:c=US;a= ;p=First Organizati;o=Exchange;s=%(username)s
proxyAddresses: SMTP:%(username)[email protected]%(dnsdomain)s
replace: msExchUserAccountControl
msExchUserAccountControl: 0
"""
        ldif_value = extended_user % {"user_dn": user_dn,
                                      "username": username,
                                      "netbiosname": names.netbiosname,
                                      "firstorg": names.firstorg,
                                      "domaindn": names.domaindn,
                                      "dnsdomain": names.dnsdomain}
        db.modify_ldif(ldif_value)

        res = db.search(base=user_dn, scope=SCOPE_BASE, attrs=["*"])
        if len(res) == 1:
            record = res[0]
        else:
            raise Exception, \
                "this should never happen as we just modified the record..."
        record_keys = map(lambda x: x.lower(), record.keys())

        if "displayname" not in record_keys:
            extended_user = "dn: %s\nadd: displayName\ndisplayName: %s\n" % (user_dn, username)
            db.modify_ldif(extended_user)

        if "mail" not in record_keys:
            extended_user = "dn: %s\nadd: mail\nmail: %[email protected]%s\n" % (user_dn, username, names.dnsdomain)
            db.modify_ldif(extended_user)

        print "[+] User %s extended and enabled" % username
    else:
        print "[!] User '%s' not found" % username
开发者ID:0x90shell,项目名称:pth-toolkit,代码行数:61,代码来源:provision.py

示例6: OpenchangeDBWithLDB

# 需要导入模块: from samba import Ldb [as 别名]
# 或者: from samba.Ldb import search [as 别名]
class OpenchangeDBWithLDB(OpenchangeDB):
    def __init__(self, uri):
        self.ldb = Ldb(uri)

    def get_calendar_uri(self, usercn, email):
        base_dn = "CN=%s,%s" % (usercn, config["samba"]["oc_user_basedn"])
        ldb_filter = "(&(objectClass=systemfolder)(PidTagContainerClass=IPF.Appointment)(MAPIStoreURI=*))"
        res = self.ldb.search(base=base_dn, scope=ldb.SCOPE_SUBTREE,
                              expression=ldb_filter, attrs=["MAPIStoreURI"])
        return [str(res[x]["MAPIStoreURI"][0]) for x in xrange(len(res))]
开发者ID:ThHirsch,项目名称:openchange,代码行数:12,代码来源:openchangedb.py

示例7: init

# 需要导入模块: from samba import Ldb [as 别名]
# 或者: from samba.Ldb import search [as 别名]
    def init(self):
        #Check to see that this 'existing' LDAP backend in fact exists
        ldapi_db = Ldb(self.ldapi_uri, credentials=self.credentials)
        search_ol_rootdse = ldapi_db.search(base="", scope=SCOPE_BASE,
                                            expression="(objectClass=OpenLDAProotDSE)")

        # If we have got here, then we must have a valid connection to the LDAP server, with valid credentials supplied
        # This caused them to be set into the long-term database later in the script.
        self.secrets_credentials = self.credentials

        self.ldap_backend_type = "openldap" #For now, assume existing backends at least emulate OpenLDAP
开发者ID:endisd,项目名称:samba,代码行数:13,代码来源:provisionbackend.py

示例8: run

# 需要导入模块: from samba import Ldb [as 别名]
# 或者: from samba.Ldb import search [as 别名]
    def run(self, secret, sambaopts=None, credopts=None, versionopts=None):
        lp = sambaopts.get_loadparm()
        creds = credopts.get_credentials(lp, fallback_machine=True)
        url = lp.get("secrets database")
        secretsdb = Ldb(url=url, session_info=system_session(),
            credentials=creds, lp=lp)
        
        result = secretsdb.search(attrs=["secret"], 
            expression="(&(objectclass=primaryDomain)(samaccountname=%s))" % secret)

        if len(result) != 1:
            raise CommandError("search returned %d records, expected 1" % len(result))

        self.outf.write("%s\n" % result[0]["secret"])
开发者ID:Alexandr-Galko,项目名称:samba,代码行数:16,代码来源:machinepw.py

示例9: start

# 需要导入模块: from samba import Ldb [as 别名]
# 或者: from samba.Ldb import search [as 别名]
    def start(self):
        self.slapd_command_escaped = "\'" + "\' \'".join(self.slapd_command) + "\'"
        open(self.paths.ldapdir + "/ldap_backend_startup.sh", 'w').write("#!/bin/sh\n" + self.slapd_command_escaped + "\n")

        # Now start the slapd, so we can provision onto it.  We keep the
        # subprocess context around, to kill this off at the successful
        # end of the script
        self.slapd = subprocess.Popen(self.slapd_provision_command, close_fds=True, shell=False)
    
        while self.slapd.poll() is None:
            # Wait until the socket appears
            try:
                ldapi_db = Ldb(self.ldapi_uri, lp=self.lp, credentials=self.credentials)
                search_ol_rootdse = ldapi_db.search(base="", scope=SCOPE_BASE,
                                                    expression="(objectClass=OpenLDAProotDSE)")
                # If we have got here, then we must have a valid connection to the LDAP server!
                return
            except LdbError, e:
                time.sleep(1)
                pass
开发者ID:endisd,项目名称:samba,代码行数:22,代码来源:provisionbackend.py

示例10: post_setup

# 需要导入模块: from samba import Ldb [as 别名]
# 或者: from samba.Ldb import search [as 别名]
    def post_setup(self):
        ldapi_db = Ldb(self.ldapi_uri, credentials=self.credentials)

        # delete default SASL mappings
        res = ldapi_db.search(expression="(!(cn=samba-admin mapping))", base="cn=mapping,cn=sasl,cn=config", scope=SCOPE_ONELEVEL, attrs=["dn"])
    
        # configure in-directory access control on Fedora DS via the aci attribute (over a direct ldapi:// socket)
        for i in range (0, len(res)):
            dn = str(res[i]["dn"])
            ldapi_db.delete(dn)
            
        aci = """(targetattr = "*") (version 3.0;acl "full access to all by samba-admin";allow (all)(userdn = "ldap:///CN=samba-admin,%s");)""" % self.sambadn
        
        m = ldb.Message()
        m["aci"] = ldb.MessageElement([aci], ldb.FLAG_MOD_REPLACE, "aci")

        m.dn = ldb.Dn(ldapi_db, self.names.domaindn)
        ldapi_db.modify(m)
            
        m.dn = ldb.Dn(ldapi_db, self.names.configdn)
        ldapi_db.modify(m)
            
        m.dn = ldb.Dn(ldapi_db, self.names.schemadn)
        ldapi_db.modify(m)
开发者ID:endisd,项目名称:samba,代码行数:26,代码来源:provisionbackend.py

示例11: system_session

# 需要导入模块: from samba import Ldb [as 别名]
# 或者: from samba.Ldb import search [as 别名]
opts = parser.parse_args()[0]
lp = sambaopts.get_loadparm()
smbconf = lp.configfile

if not opts.database:
	print "Parameter database is mandatory"
	sys.exit(1)
creds = credopts.get_credentials(lp)
creds.set_kerberos_state(DONT_USE_KERBEROS)
session = system_session()
empty = ldb.Message()
newname="%s.new"%(opts.database)
if os.path.exists(newname):
	os.remove(newname)
old_ldb = Ldb(opts.database, session_info=session, credentials=creds,lp=lp)
new_ldb = Ldb(newname,session_info=session, credentials=creds,lp=lp)

new_ldb.transaction_start()
res = old_ldb.search(expression="(dn=*)",base="", scope=SCOPE_SUBTREE)
for i in range(0,len(res)):
	if str(res[i].dn) == "@BASEINFO":
		continue
	if str(res[i].dn).startswith("@INDEX:"):
		continue
	delta = new_ldb.msg_diff(empty,res[i])
	delta.dn = res[i].dn
	delta.remove("distinguishedName")
	new_ldb.add(delta)

new_ldb.transaction_commit()
开发者ID:AllardJ,项目名称:Tomato,代码行数:32,代码来源:reorgldb.py

示例12: MapTestCase

# 需要导入模块: from samba import Ldb [as 别名]
# 或者: from samba.Ldb import search [as 别名]
class MapTestCase(MapBaseTestCase):

    def setUp(self):
        super(MapTestCase, self).setUp()
        ldb = Ldb(self.ldburl, lp=self.lp, session_info=system_session())
        ldb.set_opaque("skip_allocate_sids", "true");
        ldif = read_datafile("provision_samba3sam.ldif")
        ldb.add_ldif(self.samba4.subst(ldif))
        self.setup_modules(ldb, self.samba3, self.samba4)
        del ldb
        self.ldb = Ldb(self.ldburl, lp=self.lp, session_info=system_session())
        self.ldb.set_opaque("skip_allocate_sids", "true");

    def test_map_search(self):
        """Running search tests on mapped data."""
        self.samba3.db.add({
            "dn": "sambaDomainName=TESTS," + self.samba3.basedn,
            "objectclass": ["sambaDomain", "top"],
            "sambaSID": "S-1-5-21-4231626423-2410014848-2360679739",
            "sambaNextRid": "2000",
            "sambaDomainName": "TESTS"
            })

        # Add a set of split records
        self.ldb.add_ldif("""
dn: """+ self.samba4.dn("cn=Domain Users") + """
objectClass: group
cn: Domain Users
objectSid: S-1-5-21-4231626423-2410014848-2360679739-513
""")

        # Add a set of split records
        self.ldb.add_ldif("""
dn: """+ self.samba4.dn("cn=X") + """
objectClass: user
cn: X
codePage: x
revision: x
dnsHostName: x
nextRid: y
lastLogon: x
description: x
objectSid: S-1-5-21-4231626423-2410014848-2360679739-1052
""")

        self.ldb.add({
            "dn": self.samba4.dn("cn=Y"),
            "objectClass": "top",
            "cn": "Y",
            "codePage": "x",
            "revision": "x",
            "dnsHostName": "y",
            "nextRid": "y",
            "lastLogon": "y",
            "description": "x"})

        self.ldb.add({
            "dn": self.samba4.dn("cn=Z"),
            "objectClass": "top",
            "cn": "Z",
            "codePage": "x",
            "revision": "y",
            "dnsHostName": "z",
            "nextRid": "y",
            "lastLogon": "z",
            "description": "y"})

        # Add a set of remote records

        self.samba3.db.add({
            "dn": self.samba3.dn("cn=A"),
            "objectClass": "posixAccount",
            "cn": "A",
            "sambaNextRid": "x",
            "sambaBadPasswordCount": "x",
            "sambaLogonTime": "x",
            "description": "x",
            "sambaSID": "S-1-5-21-4231626423-2410014848-2360679739-1052",
            "sambaPrimaryGroupSID": "S-1-5-21-4231626423-2410014848-2360679739-512"})

        self.samba3.db.add({
            "dn": self.samba3.dn("cn=B"),
            "objectClass": "top",
            "cn": "B",
            "sambaNextRid": "x",
            "sambaBadPasswordCount": "x",
            "sambaLogonTime": "y",
            "description": "x"})

        self.samba3.db.add({
            "dn": self.samba3.dn("cn=C"),
            "objectClass": "top",
            "cn": "C",
            "sambaNextRid": "x",
            "sambaBadPasswordCount": "y",
            "sambaLogonTime": "z",
            "description": "y"})

        # Testing search by DN

#.........这里部分代码省略.........
开发者ID:encukou,项目名称:samba,代码行数:103,代码来源:samba3sam.py

示例13: Samba3SamTestCase

# 需要导入模块: from samba import Ldb [as 别名]
# 或者: from samba.Ldb import search [as 别名]
class Samba3SamTestCase(MapBaseTestCase):

    def setUp(self):
        super(Samba3SamTestCase, self).setUp()
        ldb = Ldb(self.ldburl, lp=self.lp, session_info=system_session())
        ldb.set_opaque("skip_allocate_sids", "true");
        self.samba3.setup_data("samba3.ldif")
        ldif = read_datafile("provision_samba3sam.ldif")
        ldb.add_ldif(self.samba4.subst(ldif))
        self.setup_modules(ldb, self.samba3, self.samba4)
        del ldb
        self.ldb = Ldb(self.ldburl, lp=self.lp, session_info=system_session())
        self.ldb.set_opaque("skip_allocate_sids", "true");

    def test_search_non_mapped(self):
        """Looking up by non-mapped attribute"""
        msg = self.ldb.search(expression="(cn=Administrator)")
        self.assertEquals(len(msg), 1)
        self.assertEquals(msg[0]["cn"], "Administrator")

    def test_search_non_mapped(self):
        """Looking up by mapped attribute"""
        msg = self.ldb.search(expression="(name=Backup Operators)")
        self.assertEquals(len(msg), 1)
        self.assertEquals(str(msg[0]["name"]), "Backup Operators")

    def test_old_name_of_renamed(self):
        """Looking up by old name of renamed attribute"""
        msg = self.ldb.search(expression="(displayName=Backup Operators)")
        self.assertEquals(len(msg), 0)

    def test_mapped_containing_sid(self):
        """Looking up mapped entry containing SID"""
        msg = self.ldb.search(expression="(cn=Replicator)")
        self.assertEquals(len(msg), 1)
        self.assertEquals(str(msg[0].dn),
                          "cn=Replicator,ou=Groups,dc=vernstok,dc=nl")
        self.assertTrue("objectSid" in msg[0])
        self.assertSidEquals("S-1-5-21-4231626423-2410014848-2360679739-1052",
                             msg[0]["objectSid"])
        oc = set(msg[0]["objectClass"])
        self.assertEquals(oc, set(["group"]))

    def test_search_by_objclass(self):
        """Looking up by objectClass"""
        msg = self.ldb.search(expression="(|(objectClass=user)(cn=Administrator))")
        self.assertEquals(set([str(m.dn) for m in msg]),
                set(["unixName=Administrator,ou=Users,dc=vernstok,dc=nl",
                     "unixName=nobody,ou=Users,dc=vernstok,dc=nl"]))

    def test_s3sam_modify(self):
        # Adding a record that will be fallbacked
        self.ldb.add({
            "dn": "cn=Foo",
            "foo": "bar",
            "blah": "Blie",
            "cn": "Foo",
            "showInAdvancedViewOnly": "TRUE"})

        # Checking for existence of record (local)
        # TODO: This record must be searched in the local database, which is
        # currently only supported for base searches
        # msg = ldb.search(expression="(cn=Foo)", ['foo','blah','cn','showInAdvancedViewOnly')]
        # TODO: Actually, this version should work as well but doesn't...
        #
        #
        msg = self.ldb.search(expression="(cn=Foo)", base="cn=Foo",
                scope=SCOPE_BASE,
                attrs=['foo','blah','cn','showInAdvancedViewOnly'])
        self.assertEquals(len(msg), 1)
        self.assertEquals(str(msg[0]["showInAdvancedViewOnly"]), "TRUE")
        self.assertEquals(str(msg[0]["foo"]), "bar")
        self.assertEquals(str(msg[0]["blah"]), "Blie")

        # Adding record that will be mapped
        self.ldb.add({"dn": "cn=Niemand,cn=Users,dc=vernstok,dc=nl",
                 "objectClass": "user",
                 "unixName": "bin",
                 "sambaUnicodePwd": "geheim",
                 "cn": "Niemand"})

        # Checking for existence of record (remote)
        msg = self.ldb.search(expression="(unixName=bin)",
                              attrs=['unixName','cn','dn', 'sambaUnicodePwd'])
        self.assertEquals(len(msg), 1)
        self.assertEquals(str(msg[0]["cn"]), "Niemand")
        self.assertEquals(str(msg[0]["sambaUnicodePwd"]), "geheim")

        # Checking for existence of record (local && remote)
        msg = self.ldb.search(expression="(&(unixName=bin)(sambaUnicodePwd=geheim))",
                         attrs=['unixName','cn','dn', 'sambaUnicodePwd'])
        self.assertEquals(len(msg), 1)           # TODO: should check with more records
        self.assertEquals(str(msg[0]["cn"]), "Niemand")
        self.assertEquals(str(msg[0]["unixName"]), "bin")
        self.assertEquals(str(msg[0]["sambaUnicodePwd"]), "geheim")

        # Checking for existence of record (local || remote)
        msg = self.ldb.search(expression="(|(unixName=bin)(sambaUnicodePwd=geheim))",
                         attrs=['unixName','cn','dn', 'sambaUnicodePwd'])
        #print "got %d replies" % len(msg)
#.........这里部分代码省略.........
开发者ID:encukou,项目名称:samba,代码行数:103,代码来源:samba3sam.py

示例14: LDAPBase

# 需要导入模块: from samba import Ldb [as 别名]
# 或者: from samba.Ldb import search [as 别名]
class LDAPBase(object):

    def __init__(self, host, creds, lp,
                 two=False, quiet=False, descriptor=False, sort_aces=False, verbose=False,
                 view="section", base="", scope="SUB",
                 outf=sys.stdout, errf=sys.stderr, skip_missing_dn=True):
        ldb_options = []
        samdb_url = host
        if not "://" in host:
            if os.path.isfile(host):
                samdb_url = "tdb://%s" % host
            else:
                samdb_url = "ldap://%s" % host
        # use 'paged_search' module when connecting remotely
        if samdb_url.lower().startswith("ldap://"):
            ldb_options = ["modules:paged_searches"]
        self.outf = outf
        self.errf = errf
        self.ldb = Ldb(url=samdb_url,
                       credentials=creds,
                       lp=lp,
                       options=ldb_options)
        self.search_base = base
        self.search_scope = scope
        self.two_domains = two
        self.quiet = quiet
        self.descriptor = descriptor
        self.sort_aces = sort_aces
        self.view = view
        self.verbose = verbose
        self.host = host
        self.skip_missing_dn = skip_missing_dn
        self.base_dn = str(self.ldb.get_default_basedn())
        self.root_dn = str(self.ldb.get_root_basedn())
        self.config_dn = str(self.ldb.get_config_basedn())
        self.schema_dn = str(self.ldb.get_schema_basedn())
        self.domain_netbios = self.find_netbios()
        self.server_names = self.find_servers()
        self.domain_name = re.sub("[Dd][Cc]=", "", self.base_dn).replace(",", ".")
        self.domain_sid = self.find_domain_sid()
        self.get_sid_map()
        #
        # Log some domain controller specific place-holers that are being used
        # when compare content of two DCs. Uncomment for DEBUG purposes.
        if self.two_domains and not self.quiet:
            self.outf.write("\n* Place-holders for %s:\n" % self.host)
            self.outf.write(4*" " + "${DOMAIN_DN}      => %s\n" %
                self.base_dn)
            self.outf.write(4*" " + "${DOMAIN_NETBIOS} => %s\n" %
                self.domain_netbios)
            self.outf.write(4*" " + "${SERVER_NAME}     => %s\n" %
                self.server_names)
            self.outf.write(4*" " + "${DOMAIN_NAME}    => %s\n" %
                self.domain_name)

    def find_domain_sid(self):
        res = self.ldb.search(base=self.base_dn, expression="(objectClass=*)", scope=SCOPE_BASE)
        return ndr_unpack(security.dom_sid,res[0]["objectSid"][0])

    def find_servers(self):
        """
        """
        res = self.ldb.search(base="OU=Domain Controllers,%s" % self.base_dn,
                scope=SCOPE_SUBTREE, expression="(objectClass=computer)", attrs=["cn"])
        assert len(res) > 0
        srv = []
        for x in res:
            srv.append(x["cn"][0])
        return srv

    def find_netbios(self):
        res = self.ldb.search(base="CN=Partitions,%s" % self.config_dn,
                scope=SCOPE_SUBTREE, attrs=["nETBIOSName"])
        assert len(res) > 0
        for x in res:
            if "nETBIOSName" in x.keys():
                return x["nETBIOSName"][0]

    def object_exists(self, object_dn):
        res = None
        try:
            res = self.ldb.search(base=object_dn, scope=SCOPE_BASE)
        except LdbError as e:
            (enum, estr) = e.args
            if enum == ERR_NO_SUCH_OBJECT:
                return False
            raise
        return len(res) == 1

    def delete_force(self, object_dn):
        try:
            self.ldb.delete(object_dn)
        except Ldb.LdbError as e:
            assert "No such object" in str(e)

    def get_attribute_name(self, key):
        """ Returns the real attribute name
            It resolved ranged results e.g. member;range=0-1499
        """

#.........这里部分代码省略.........
开发者ID:sYnfo,项目名称:samba,代码行数:103,代码来源:ldapcmp.py

示例15: checkusage

# 需要导入模块: from samba import Ldb [as 别名]
# 或者: from samba.Ldb import search [as 别名]
def checkusage(names, lp, creds):
    """Checks whether this server is already provisioned and is being used.

    :param names: provision names object.
    :param lp: Loadparm context
    :param creds: Credentials Context
    """

    samdb = get_local_samdb(names, lp, creds)

    try:
        config_dn = samdb.get_config_basedn()
        mapi_servers = samdb.search(
            base=config_dn, scope=ldb.SCOPE_SUBTREE,
            expression="(&(objectClass=msExchExchangeServer)(cn=%s))" % names.netbiosname)
        server_uses = []

        if len(mapi_servers) == 0:
            # The server is not provisioned.
            raise NotProvisionedError

        if len(mapi_servers) > 1:
            # Check if we are the primary folder store server.
            our_siteFolderName = "CN=Public Folder Store (%s),CN=First Storage Group,CN=InformationStore,CN=%s,CN=Servers,CN=%s,CN=AdministrativeGroups,%s" % (names.netbiosname, names.netbiosname, names.firstou, names.firstorgdn)
            dn = "CN=%s,CN=Administrative Groups,%s" % (names.firstou,
                                                        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():
                server_uses.append("primary folder store server")

            # Check if we are the primary receipt update service
            our_addressListServiceLink = "CN=%s,CN=Servers,CN=%s,CN=Administrative Groups,%s" % (names.netbiosname, names.firstou, 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():
                server_uses.append("primary receipt update service server")

        # Check if we handle any mailbox.
        db = Ldb(
            url=get_ldb_url(lp, creds, names), session_info=system_session(),
            credentials=creds, lp=lp)

        our_mailbox_store = "CN=Mailbox Store (%s),CN=First Storage Group,CN=InformationStore,CN=%s,CN=Servers,CN=%s,CN=Administrative Groups,%s" % (names.netbiosname, names.netbiosname, names.firstou, names.firstorgdn)
        mailboxes = db.search(
            base=names.domaindn, scope=ldb.SCOPE_SUBTREE,
            expression="(homeMDB=*)")
        mailboxes_handled = 0
        for user_mailbox in mailboxes:
            if (user_mailbox['homeMDB'][0] == our_mailbox_store and
                  user_mailbox['msExchUserAccountControl'][0] != '2'):
                mailboxes_handled += 1

        if mailboxes_handled > 0:
            server_uses.append("handling %d mailboxes" % mailboxes_handled)

        return server_uses
    except LdbError, ldb_error:
        print >> sys.stderr, "[!] error while checking whether this server is being used (%d): %s" % ldb_error.args
        raise ldb_error
开发者ID:mactalla,项目名称:openchange,代码行数:65,代码来源:provision.py


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