Beispiel #1
0
    def do_explode_dn(self, argstr):
        """Explode DN.
usage: explode_dn dn
"""
        if not argstr:
            print "error: No DN specified"

        print ldap.explode_dn(argstr)
Beispiel #2
0
    def swap(self):
        """Make the conflict entry the real valid entry.  Delete old valid entry,
        and rename the conflict
        """

        # Get the conflict entry info
        conflict_value = self.get_attr_val_utf8('nsds5ReplConflict')
        entry_dn = conflict_value.split(' ', 2)[2]
        entry_rdn = ldap.explode_dn(entry_dn, 1)[0]

        # Gather the RDN details
        rdn_attr = entry_dn.split('=', 1)[0]
        new_rdn = "{}={}".format(rdn_attr, entry_rdn)
        tmp_rdn = new_rdn + 'tmp'

        # Delete valid entry and its children (to be replaced by conflict entry)
        original_entry = DSLdapObject(self._instance, dn=entry_dn)
        original_entry._protected = False
        filterstr = "(|(objectclass=*)(objectclass=ldapsubentry))"
        ents = self._instance.search_s(original_entry._dn, ldap.SCOPE_SUBTREE, filterstr, escapehatch='i am sure')
        for ent in sorted(ents, key=lambda e: len(e.dn), reverse=True):
            self._instance.delete_ext_s(ent.dn, serverctrls=self._server_controls, clientctrls=self._client_controls, escapehatch='i am sure')

        # Rename conflict entry to tmp rdn so we can clean up the rdn attr
        self.rename(tmp_rdn, deloldrdn=False)

        # Cleanup entry
        self.remove(rdn_attr, entry_rdn)
        if self.present('objectclass', 'ldapsubentry'):
            self.remove('objectclass', 'ldapsubentry')
        self.remove_all('nsds5ReplConflict')

        # Rename to the final/correct rdn
        self.rename(new_rdn, deloldrdn=True)
Beispiel #3
0
    def rename(self, new_rdn, newsuperior=None, deloldrdn=True):
        """Renames the object within the tree.

        If you provide a newsuperior, this will move the object in the tree.
        If you only provide a new_rdn, it stays in the same branch, but just
        changes the rdn.

        Note, if you use newsuperior, you may move this object outside of the
        scope of the related DSLdapObjects manager, which may cause it not to
        appear in .get() requests.

        :param new_rdn: RDN of the new entry
        :type new_rdn: str
        :param newsuperior: New parent DN
        :type newsuperior: str
        """
        # When we are finished with this, we need to update our DN
        # To do this, we probably need to search the new rdn as a filter,
        # and the superior as the base (if it changed)
        if self._protected:
            return

        self._instance.rename_s(self._dn, new_rdn, newsuperior,
                                serverctrls=self._server_controls, clientctrls=self._client_controls,
                                delold=deloldrdn, escapehatch='i am sure')
        if newsuperior is not None:
            # Well, the new DN should be rdn + newsuperior.
            self._dn = '%s,%s' % (new_rdn, newsuperior)
        else:
            old_dn_parts = ldap.explode_dn(self._dn)
            # Replace the rdn
            old_dn_parts[0] = new_rdn
            self._dn = ",".join(old_dn_parts)
        assert self.exists()
Beispiel #4
0
    def cleanDN(self, dnString):
        tmpList = []

        for x in ldap.explode_dn(dnString):
            tmpList.append(self.escape_dn_chars(x))

        return ",".join(tmpList)
    def getusers_searchbase(self, config, data):
        for ldapuser in data:
            self.count += 1
            ldapuser = ldapuser[1]
            try:
                firstname = ldapuser[config.ldap_attrs['firstname']][0]
                lastname = ldapuser[config.ldap_attrs['lastname']][0]
                username = ldap_get_username(config.ldap_attrs['username'], config.google_apps_domain, ldapuser)

                if 'userAccountControl' in config.ldap_attrs and config.ldap_exclude_disabled:
                    # AD uses the second bit of userAccountControl to indicate a disabled account.
                    if 2 & int(ldapuser[config.ldap_attrs['userAccountControl']][0]):
                        print "disabled: %s %s,%s" % (username, lastname, firstname)
                        continue


                # drop the timezone portion of whenChanged (example: '20110526184938.0Z' -> '20110526184938'
                whenchanged = ldapuser[config.ldap_attrs['whenchanged']][0].split('.')[0]

                ous = ['/']
                if 'ous' in config.ldap_attrs:
                    ous = ldap.explode_dn(ldapuser[config.ldap_attrs['ous']][0].lower())
                    ous = map(lambda x: x[3:], filter(lambda x: re.match('ou=', x), ous))
                    ous.reverse()
                #sys.stdout.write("%s %s %s: " % (ldapuser['givenName'][0], ldapuser['sn'][0], ldapuser['sAMAccountName'][0]))
            except KeyError, inst:
                print "exception: %s:%s" % (type(inst), inst)
                print ldapuser
                continue
            except AssertionError, inst:
                print "exception: %s:%s" % (type(inst), inst)
                print ldapuser
                continue
Beispiel #6
0
 def get_name_from_dn(cls, dn):
     if dn:
         try:
             name = explode_dn(dn, 1)[0]
         except ldap.DECODING_ERROR:
             name = ''
         return cls._meta.ldap_unmap_function([name])
def udm_remove_dns_record_object(module, object_dn):
    superordinate = ",".join(ldap.explode_dn(object_dn)[1:])
    cmd = [
        '/usr/sbin/udm-test', module, 'remove', '--dn', object_dn,
        '--superordinate', superordinate
    ]
    return subprocess.call(cmd)
Beispiel #8
0
 def move(self, dn, new_parent, new_rdn=None):
     """
     Move and/or rename an LDAP entry.
     """
     if not new_rdn:
         new_rdn = ldap.explode_dn(dn)[0]
     self.ldap_handle.rename_s(dn, new_rdn, newsuperior=new_parent, delold=1)
Beispiel #9
0
def comment_by_query(jira_instance, query, comment, cc_to_manager, ldap_server,
                     basedn):
    """Adds a comment to tickets of the specified epic that are in the TODO
       state. and adds a CC to the users manager"""

    print("Add Comment to tickets in query results")

    for issue in jira_instance.search_issues(query, maxResults=400):
        assignee = issue.fields.assignee.key
        if cc_to_manager:
            # this is here because it is only required for this part of this
            # function. So it is not a requirement for the whole script
            import ldap
            l = ldap.initialize(ldap_server)
            l_filter = "uid=%s" % assignee
            l_attr = ["manager"]
            l_scope = ldap.SCOPE_SUBTREE
            ldap_result_id = l.search(basedn, l_scope, l_filter, l_attr)
            # only expecting a single result per query
            result_type, result_data = l.result(ldap_result_id, 0)
            if result_data:
                manager_dn = result_data[0][1]["manager"][0]
                manager = ldap.explode_dn(manager_dn)[0].split("=")[1]
                newcomment = "CC: [~%s]\n\n%s" % \
                    (manager, comment)
        else:
            newcomment = comment
        jira_instance.add_comment(issue.key, newcomment)
Beispiel #10
0
    def open(self):
        univention.admin.handlers.simpleLdap.open(self)

        if self.dn:
            self['name'] = ldap.explode_dn(self.dn, 1)[0]

            self['dnsForwardZone'] = ''
            self['dnsReverseZone'] = ''
            forward = self.lo.searchDn(
                base=self.dn,
                scope='domain',
                filter=
                '(&(objectClass=dNSZone)(relativeDomainName=@)(!(zoneName=*.in-addr.arpa)))'
            )
            for f in forward:
                self['dnsForwardZone'].append(f)
            reverse = self.lo.searchDn(
                base=self.dn,
                scope='domain',
                filter=
                '(&(objectClass=dNSZone)(relativeDomainName=@)(zoneName=*.in-addr.arpa))'
            )
            for r in reverse:
                self['dnsReverseZone'].append(r)

            if not 'krb5Realm' in self.oldattr.get('objectClass', []):
                iself._remove_option('kerberos')
Beispiel #11
0
    def cleanDN(self, dnString):
        tmpList = []

        for x in ldap.explode_dn(dnString):
            tmpList.append(self.escape_dn_chars(x))

        return ",".join(tmpList)
Beispiel #12
0
def normalizeDN(dn, usespace=False):
    # not great, but will do until we use a newer version of python-ldap
    # that has DN utilities
    ary = ldap.explode_dn(dn.lower())
    joinstr = ","
    if usespace:
        joinstr = ", "
    return joinstr.join(ary)
Beispiel #13
0
def computerdn(dn1,dn2):
    """return the rdn part of dn1 based on dn2"""
    a=ldap.explode_dn(dn1)
    b=ldap.explode_dn(dn2)
    if b=="":
        return dn1
    l_a=len(a)
    l_b=len(b)
    if l_a<l_b:
        raise RdnError, "Lenth of base dn is longer than the compared one."
    if a[l_a-l_b:]==b:
        if l_a!=l_b:
            return reduce(lambda x,y:x+", "+y, a[:l_a-l_b])
        else:
            return ""
    else:
        raise RdnError, "The dn is mismatch."
Beispiel #14
0
def normalizeDN(dn, usespace=False):
    # not great, but will do until we use a newer version of python-ldap
    # that has DN utilities
    ary = ldap.explode_dn(dn.lower())
    joinstr = ","
    if usespace:
        joinstr = ", "
    return joinstr.join(ary)
Beispiel #15
0
def computerdn(dn1, dn2):
    """return the rdn part of dn1 based on dn2"""
    a = ldap.explode_dn(dn1)
    b = ldap.explode_dn(dn2)
    if b == "":
        return dn1
    l_a = len(a)
    l_b = len(b)
    if l_a < l_b:
        raise RdnError, "Lenth of base dn is longer than the compared one."
    if a[l_a - l_b:] == b:
        if l_a != l_b:
            return reduce(lambda x, y: x + ", " + y, a[:l_a - l_b])
        else:
            return ""
    else:
        raise RdnError, "The dn is mismatch."
Beispiel #16
0
def __split_s4_dn(dn):
    # split zone
    dn = ldap.explode_dn(dn)

    # split the DC= from the zoneName
    zoneName = string.join(dn[1].split('=')[1:], '=')
    relativeDomainName = string.join(dn[0].split('=')[1:], '=')

    return (zoneName, relativeDomainName)
Beispiel #17
0
def __split_s4_dn(dn):
	# split zone
	dn=ldap.explode_dn(dn)

	# split the DC= from the zoneName
	zoneName=string.join(dn[1].split('=')[1:], '=')
	relativeDomainName=string.join(dn[0].split('=')[1:], '=')

	return (zoneName, relativeDomainName)
Beispiel #18
0
    def getdn(self, section, option):
        """
        Like get, but interpret the value as a LDAP DN, and sanitize it by
        removing the extra spaces.

        If the value is not a valid DN, a ldap.LDAPError exception will be
        raised.
        """
        return ",".join(ldap.explode_dn(self.get(section, option)))
 def explode_dn(self, dn, notypes=0):
     """ Indirection to avoid need for importing ldap elsewhere """
     exploded = []
     for dn_part in ldap.explode_dn(dn, notypes):
         if isinstance(dn_part, six.text_type):
             exploded.append(dn_part.encode('UTF-8'))
         else:
             exploded.append(dn_part)
     return exploded
Beispiel #20
0
    def getdn(self, section, option):
        """
        Like get, but interpret the value as a LDAP DN, and sanitize it by
        removing the extra spaces.

        If the value is not a valid DN, a ldap.LDAPError exception will be
        raised.
        """
        return ",".join(ldap.explode_dn(self.get(section, option)))
Beispiel #21
0
    def normalizedn(self, dn):
        """
        normalizedn

        Returns
        -------
            string
        """
        explodeddn = ldap.explode_dn(dn)
        return string.join(explodeddn, ',')
Beispiel #22
0
    def __init__(self, db, dn, attributes):
        AbstractResultEntry.__init__(self, db)
        self.name = dn
        self.attributes = attributes

        # Get the tag
        explodeddn = ldap.explode_dn(dn)
        rdn = explodeddn[0]
        matchobj = _Att.match(rdn)
        if matchobj is None:
            raise IndexError(InvalidEntryName + dn)

        self.tag = matchobj.group(1)
Beispiel #23
0
    def __init__(self, db, dn, attributes):
        AbstractResultEntry.__init__(self, db)
        self.name = dn
        self.attributes = attributes

        # Get the tag
        explodeddn = ldap.explode_dn(dn)
        rdn = explodeddn[0]
        matchobj = _Att.match(rdn)
        if matchobj is None:
            raise IndexError, InvalidEntryName + dn

        self.tag = matchobj.group(1)
Beispiel #24
0
def explode_dn(dn, charset='utf-8'):
    """
  Wrapper function for explode_dn() which returns [] for 
  a zero-length DN
  """
    if not dn:
        return []
    if type(dn) == UnicodeType:
        dn = dn.encode(charset)
    dn_list = ldap.explode_dn(dn.strip())
    if dn_list and dn_list != ['']:
        return [unicode(dn.strip(), charset) for dn in dn_list]
    else:
        return []
Beispiel #25
0
	def open(self):
		univention.admin.handlers.simpleLdap.open(self)

		if self.exists():
			self['name'] = ldap.explode_dn(self.dn, 1)[0]

			self['dnsForwardZone'] = ''
			self['dnsReverseZone'] = ''
			forward = self.lo.searchDn(base=self.dn, scope='domain', filter='(&(objectClass=dNSZone)(relativeDomainName=@)(!(zoneName=*.in-addr.arpa)))')
			for f in forward:
				self['dnsForwardZone'].append(f)
			reverse = self.lo.searchDn(base=self.dn, scope='domain', filter='(&(objectClass=dNSZone)(relativeDomainName=@)(zoneName=*.in-addr.arpa))')
			for r in reverse:
				self['dnsReverseZone'].append(r)
Beispiel #26
0
    def getParcPrinters (self, parc):
        """
            Return a list of all parc's printers
        """
        printers = []
        dnList = self.__search (self.__parcsRdn, "(&(cn=%s)(objectClass=groupOfNames))" \
                                % parc, "member")
        defaultPrinterDnList = \
        self.__search (self.__parcsRdn, "(&(cn=%s)(objectClass=groupOfNames))" \
                                % parc, "owner")
        if len ((defaultPrinterDnList)):
            defaultPrinter = ldap.explode_dn (defaultPrinterDnList[0], 1)[0]
        else:
            defaultPrinter = ""

        for dn in dnList:
            rdnList = ldap.explode_dn (dn, 1)
            if rdnList[1] == "Printers":
                if rdnList[0] == defaultPrinter:
                    printers.insert (0, defaultPrinter)
                else:
                    printers.append (rdnList[0])
 
        return printers
Beispiel #27
0
 def do_cd(self, argstr):
     """Change default location in directory."""
     if argstr:
         args = split_args(argstr)
         dn = args[0]
         if args[0] == "..":
             dn_comps = ldap.explode_dn(self.dn)
             dn = ",".join(dn_comps[1:])
             self.dn = dn
         elif args[0] == ".":
             return
         else:
             dn = self.get_dn(dn)
             self.dn = dn
         self.prompt = "ldapsh %s> " % dn
Beispiel #28
0
    def getObjFromDataset(self, dn):

        # Get the parent dataset
        explodeddn = ldap.explode_dn(dn)
        dsetdn = string.join(explodeddn[1:],',') # Dataset node is parent of variable
        dset = self.getDataset(dsetdn)
        rdn = explodeddn[0]
        matchobj = _Att.match(rdn)
        if matchobj is None:
            raise CDMSError, InvalidEntryName +  dn
        tag, id = matchobj.groups()

        # Get the correct dictionary for this tag
        dict = dset.dictdict[tag]
        obj = dict[id]
        return obj
Beispiel #29
0
    def getObjFromDataset(self, dn):

        # Get the parent dataset
        explodeddn = ldap.explode_dn(dn)
        # Dataset node is parent of variable
        dsetdn = string.join(explodeddn[1:], ',')
        dset = self.getDataset(dsetdn)
        rdn = explodeddn[0]
        matchobj = _Att.match(rdn)
        if matchobj is None:
            raise CDMSError(InvalidEntryName + dn)
        tag, id = matchobj.groups()

        # Get the correct dictionary for this tag
        dict = dset.dictdict[tag]
        obj = dict[id]
        return obj
Beispiel #30
0
	def open(self):
		univention.admin.handlers.simpleLdap.open(self)

		if self.dn:
			self['name']=ldap.explode_dn(self.dn,1)[0]

			
			self['dnsForwardZone']=''
			self['dnsReverseZone']=''
			forward=self.lo.searchDn(base=self.dn, scope='domain', filter='(&(objectClass=dNSZone)(relativeDomainName=@)(!(zoneName=*.in-addr.arpa)))')
			for f in forward:
				self['dnsForwardZone'].append(f)
			reverse=self.lo.searchDn(base=self.dn, scope='domain', filter='(&(objectClass=dNSZone)(relativeDomainName=@)(zoneName=*.in-addr.arpa))')
			for r in reverse:
				self['dnsReverseZone'].append(r)

			if not 'krb5Realm' in self.oldattr.get('objectClass', []):
				iself._remove_option('kerberos')
Beispiel #31
0
def addouent(ds,dn):
    pdns = [dn]
    while len(pdns) > 0:
        dn = pdns.pop()
        ent = Entry(dn)
        ent.setValues('objectclass', 'organizationalUnit')
        try:
            ds.add_s(ent)
            print "added entry", ent.dn
        except ldap.ALREADY_EXISTS:
            continue
        except ldap.NO_SUCH_OBJECT:
            pdns.append(dn)
            rdns = ldap.explode_dn(dn)
            pdn = ','.join(rdns[1:])
            pdns.append(pdn)
        except Exception, e:
            print "Could not add entry", ent.dn, str(e)
            raise e
Beispiel #32
0
def addouent(ds, dn):
    pdns = [dn]
    while len(pdns) > 0:
        dn = pdns.pop()
        ent = Entry(dn)
        ent.setValues('objectclass', 'organizationalUnit')
        try:
            ds.add_s(ent)
            print "added entry", ent.dn
        except ldap.ALREADY_EXISTS:
            continue
        except ldap.NO_SUCH_OBJECT:
            pdns.append(dn)
            rdns = ldap.explode_dn(dn)
            pdn = ','.join(rdns[1:])
            pdns.append(pdn)
        except Exception, e:
            print "Could not add entry", ent.dn, str(e)
            raise e
Beispiel #33
0
    def create(self, rdn=None, properties=None, basedn=None):
        """Create the link entry, and the mapping tree entry(if needed)
        """

        # Create chaining entry
        super(ChainingLink, self).create(rdn, properties, basedn)

        # Create mapping tree entry
        dn_comps = ldap.explode_dn(properties['nsslapd-suffix'][0])
        parent_suffix = ','.join(dn_comps[1:])
        mt_properties = {
            'cn': properties['nsslapd-suffix'][0],
            'nsslapd-state': 'backend',
            'nsslapd-backend': properties['cn'][0],
            'nsslapd-parent-suffix': parent_suffix
        }
        try:
            self._mts.ensure_state(properties=mt_properties)
        except ldap.ALREADY_EXISTS:
            pass
Beispiel #34
0
def get_users(self, l, key, keyword):
    """
        Get all members of a given groupname
        returns a list of uids
    """

    base = group_base(self)
    scope = ldap.SCOPE_SUBTREE
    filter = key + "=" + "*" + keyword + "*"
    retrieve_attributes = ('uniqueMember', )
    count = 0
    result_set = []
    timeout = 0
    try:
        result_id = l.search(base, scope, filter, retrieve_attributes)
        while l:
            result_type, result_data = l.result(result_id, timeout)
            if (result_data == []):
                break
            else:
                if result_type == ldap.RES_SEARCH_ENTRY:
                    result_set.append(result_data)

            if len(result_set) == 0:
                print "No Results."
                uids = []
        #print "len",len(result_set)
        uids = []
        for i in range(len(result_set)):
            for entry in result_set[i]:
                try:
                    for member in entry[1]['uniqueMember']:
                        uid = ldap.explode_dn(member, notypes=1)[0]
                        #print uid
                        uids.append(uid)
                    count = count + 1
                except:
                    pass

    except ldap.LDAPError, error_message:
        print error_message
Beispiel #35
0
def getadminport(cfgconn, cfgdn, args):
    """Return a 2-tuple (asport, True) if the admin server is using SSL,
    False otherwise.

    Get the admin server port so we can contact it via http.  We get this from
    the configuration entry using the CFGSUFFIX and cfgconn.  Also get any
    other information we may need from that entry.
    """
    asport = 0
    secure = False
    if cfgconn:
        dn = cfgdn
        if 'admin_domain' in args:
            dn = "cn=%s,ou=%s, %s" % (
                args[SER_HOST], args['admin_domain'], cfgdn)
        filt = "(&(objectclass=nsAdminServer)(serverHostName=%s)" % args[
            SER_HOST]
        if 'sroot' in args:
            filt += "(serverRoot=%s)" % args['sroot']
        filt += ")"
        ent = cfgconn.getEntry(
            dn, ldap.SCOPE_SUBTREE, filt, ['serverRoot'])
        if ent:
            if 'sroot' not in args and ent.serverRoot:
                args['sroot'] = ent.serverRoot
            if 'admin_domain' not in args:
                ary = ldap.explode_dn(ent.dn, 1)
                args['admin_domain'] = ary[-2]
            dn = "cn=configuration, " + ent.dn
            ent = cfgconn.getEntry(dn, ldap.SCOPE_BASE, '(objectclass=*)',
                                   ['nsServerPort',
                                    'nsSuiteSpotUser',
                                    'nsServerSecurity'])
            if ent:
                asport = ent.nsServerPort
                secure = (ent.nsServerSecurity and (
                    ent.nsServerSecurity == 'on'))
                if 'newuserid' not in args:
                    args['newuserid'] = ent.nsSuiteSpotUser
        cfgconn.unbind()
    return asport, secure
def getadminport(cfgconn, cfgdn, args):
    """Return a 2-tuple (asport, True) if the admin server is using SSL,
    False otherwise.

    Get the admin server port so we can contact it via http.  We get this from
    the configuration entry using the CFGSUFFIX and cfgconn.  Also get any
    other information we may need from that entry.
    """
    asport = 0
    secure = False
    if cfgconn:
        dn = cfgdn
        if 'admin_domain' in args:
            dn = "cn=%s,ou=%s, %s" % (
                args[SER_HOST], args['admin_domain'], cfgdn)
        filt = "(&(objectclass=nsAdminServer)(serverHostName=%s)" % args[
            SER_HOST]
        if 'sroot' in args:
            filt += "(serverRoot=%s)" % args['sroot']
        filt += ")"
        ent = cfgconn.getEntry(
            dn, ldap.SCOPE_SUBTREE, filt, ['serverRoot'])
        if ent:
            if 'sroot' not in args and ent.serverRoot:
                args['sroot'] = ent.serverRoot
            if 'admin_domain' not in args:
                ary = ldap.explode_dn(ent.dn, 1)
                args['admin_domain'] = ary[-2]
            dn = "cn=configuration, " + ent.dn
            ent = cfgconn.getEntry(dn, ldap.SCOPE_BASE, '(objectclass=*)',
                                   ['nsServerPort',
                                    'nsSuiteSpotUser',
                                    'nsServerSecurity'])
            if ent:
                asport = ent.nsServerPort
                secure = (ent.nsServerSecurity and (
                    ent.nsServerSecurity == 'on'))
                if 'newuserid' not in args:
                    args['newuserid'] = ent.nsSuiteSpotUser
        cfgconn.unbind()
    return asport, secure
Beispiel #37
0
    def __init__(self, dn, attrs=None, connection=None, isNew=0):
        self.id=ldap.explode_dn(dn)[0]  #split the DN into a list.
        self.dn=dn                      #Our actually unique ID in tree
        self._p_jar=None                #actually, the connection
        self._setConnection(None)

        if attrs is None and connection is not None:
            self._init(connection)
        elif attrs and connection is not None:
            self._data=attrs
            self._p_jar=connection
            self._setConnection(connection)
        else:
            self._data={}
        self._isNew=isNew
        if isNew:
            get_transaction().register(self)
            self._registered=1
        self._isDeleted=0               #deletion flag
        self._clearSubentries()
        self._mod_delete=[]
Beispiel #38
0
    def __init__(self, dn, attrs=None, connection=None, isNew=0):
        self.id = ldap.explode_dn(dn)[0]  #split the DN into a list.
        self.dn = dn  #Our actually unique ID in tree
        self._p_jar = None  #actually, the connection
        self._setConnection(None)

        if attrs is None and connection is not None:
            self._init(connection)
        elif attrs and connection is not None:
            self._data = attrs
            self._p_jar = connection
            self._setConnection(connection)
        else:
            self._data = {}
        self._isNew = isNew
        if isNew:
            transaction.get().register(self)
            self._registered = 1
        self._isDeleted = 0  #deletion flag
        self._clearSubentries()
        self._mod_delete = []
    def getusers_searchbase(self, config, data):
        for ldapuser in data:
            self.count += 1
            ldapuser = ldapuser[1]
            try:
                firstname = ldapuser[config.ldap_attrs['firstname']][0]
                lastname = ldapuser[config.ldap_attrs['lastname']][0]
                username = ldap_get_username(config.ldap_attrs['username'],
                                             config.google_apps_domain,
                                             ldapuser)

                if 'userAccountControl' in config.ldap_attrs and config.ldap_exclude_disabled:
                    # AD uses the second bit of userAccountControl to indicate a disabled account.
                    if 2 & int(ldapuser[
                            config.ldap_attrs['userAccountControl']][0]):
                        print "disabled: %s %s,%s" % (username, lastname,
                                                      firstname)
                        continue

                # drop the timezone portion of whenChanged (example: '20110526184938.0Z' -> '20110526184938'
                whenchanged = ldapuser[
                    config.ldap_attrs['whenchanged']][0].split('.')[0]

                ous = ['/']
                if 'ous' in config.ldap_attrs:
                    ous = ldap.explode_dn(
                        ldapuser[config.ldap_attrs['ous']][0].lower())
                    ous = map(lambda x: x[3:],
                              filter(lambda x: re.match('ou=', x), ous))
                    ous.reverse()
                #sys.stdout.write("%s %s %s: " % (ldapuser['givenName'][0], ldapuser['sn'][0], ldapuser['sAMAccountName'][0]))
            except KeyError, inst:
                print "exception: %s:%s" % (type(inst), inst)
                print ldapuser
                continue
            except AssertionError, inst:
                print "exception: %s:%s" % (type(inst), inst)
                print ldapuser
                continue
Beispiel #40
0
    def convert(self, new_rdn):
        """Convert conflict entry to a valid entry, but we need to
        give the conflict entry a new rdn since we are not replacing
        the existing valid counterpart entry.
        """

        if not is_a_dn(new_rdn):
            raise ValueError("The new RDN (" + new_rdn + ") is not a valid DN")

        # Get the conflict entry info
        conflict_value = self.get_attr_val_utf8('nsds5ReplConflict')
        entry_dn = conflict_value.split(' ', 2)[2]
        entry_rdn = ldap.explode_dn(entry_dn, 1)[0]
        rdn_attr = entry_dn.split('=', 1)[0]

        # Rename conflict entry
        self.rename(new_rdn, deloldrdn=False)

        # Cleanup entry
        self.remove(rdn_attr, entry_rdn)
        if self.present('objectclass', 'ldapsubentry'):
            self.remove('objectclass', 'ldapsubentry')
        self.remove_all('nsds5ReplConflict')
Beispiel #41
0
    def do_ls(self, argstr):
        """Display list of entries.
usage: ls [location]
location defaults to current location
"""
        if not self.conn:
            print "Not bound to directory."
            return

        dn = self.dn
        if argstr:
            args = split_args(argstr)
            if len(args):
                dn = args[0]
        try:
            result = self.conn.search_s(dn, ldap.SCOPE_ONELEVEL,
                                        "objectclass=*")
            for entry in result:
                rdns = ldap.explode_dn(entry[0])
                dn_index = self.cache_dn(entry[0])
                print "%d %s" % (dn_index, rdns[0])
        except LDAPError, e:
            print "error:", sys.exc_type, e
Beispiel #42
0
    def __init__(self, dn, attrs=None, connection=None, isNew=0):
        self.id = ldap.explode_dn(dn)[0] # Split the DN into a list.
        self.dn = dn                    # Our actually unique ID in tree
        self.__connection = None

        if attrs is None and connection is not None:
            # We have no passed in attributes, but we do have a connection
            # to get them from.
            self._init(connection)
        elif attrs and connection is not None:
            # Attributes were passed in, so we don't need to go to our
            # connection to retrieve them
            self._data = attrs
            self.__connection = connection
        else:
            # We're totally blank and disconnected
            self._data = {}

        self._isNew = isNew
        if isNew:
            pass                        # XXX need to handle creation here
        self._isDeleted = 0             # Deletion flag
        self.__subentries = {}          # subentries
        self._mod_delete = []
Beispiel #43
0
    def __init__(self, dn, attrs=None, connection=None, isNew=0):
        self.id = ldap.explode_dn(dn)[0]  # Split the DN into a list.
        self.dn = dn  # Our actually unique ID in tree
        self.__connection = None

        if attrs is None and connection is not None:
            # We have no passed in attributes, but we do have a connection
            # to get them from.
            self._init(connection)
        elif attrs and connection is not None:
            # Attributes were passed in, so we don't need to go to our
            # connection to retrieve them
            self._data = attrs
            self.__connection = connection
        else:
            # We're totally blank and disconnected
            self._data = {}

        self._isNew = isNew
        if isNew:
            pass  # XXX need to handle creation here
        self._isDeleted = 0  # Deletion flag
        self.__subentries = {}  # subentries
        self._mod_delete = []
Beispiel #44
0
def activate():
    """
     this function define if the module "base" can be activated.
     @return: return True if this module can be activate
     @rtype: boolean
    """
    config = SambaConfig("samba")

    if config.disabled:
        logger.info("samba plugin disabled by configuration.")
        return False

    if config.defaultSharesPath:
        if config.defaultSharesPath.endswith("/"):
            logger.error("Trailing / is not allowed in defaultSharesPath")
            return False
        if not os.path.exists(config.defaultSharesPath):
            logger.error("The default shares path '%s' does not exist" %
                         config.defaultSharesPath)
            return False

    for cpath in config.authorizedSharePaths:
        if cpath.endswith("/"):
            logger.error("Trailing / is not allowed in authorizedSharePaths")
            return False
        if not os.path.exists(cpath):
            logger.error("The authorized share path '%s' does not exist" %
                         cpath)
            return False

    # Verify if samba conf file exist
    conf = config.samba_conf_file
    if not os.path.exists(conf):
        logger.error(conf + " does not exist")
        return False

    # validate smb.conf
    smbconf = SambaConf()
    if not smbconf.validate(conf):
        logger.error("SAMBA configuration file is not valid")
        return False

    # For each share, test if it sharePath exists
    for share in getDetailedShares():
        shareName = share[0]
        infos = shareInfo(shareName)
        if infos:
            sharePath = infos['sharePath']
            if sharePath and not '%' in sharePath and not os.path.exists(
                    sharePath):
                # only show error
                logger.error("The samba share path '%s' does not exist." %
                             sharePath)
        else:
            return False

    try:
        ldapObj = ldapUserGroupControl()
    except ldap.INVALID_CREDENTIALS:
        logger.error("Can't bind to LDAP: invalid credentials.")
        return False

    # Test if the Samba LDAP schema is available in the directory
    try:
        schema = ldapObj.getSchema("sambaSamAccount")
        if len(schema) <= 0:
            logger.error("Samba schema is not included in LDAP directory")
            return False
    except:
        logger.exception("invalid schema")
        return False

    # Verify if init script exist
    init = config.samba_init_script
    if not os.path.exists(init):
        logger.error(init + " does not exist")
        return False

    # If SAMBA is defined as a PDC, make extra checks
    if smbconf.isPdc():
        samba = SambaLDAP()
        # Create SAMBA computers account OU if it doesn't exist
        head, path = samba.baseComputersDN.split(",", 1)
        ouName = head.split("=")[1]
        samba.addOu(ouName, path)
        # Check that a sambaDomainName entry is in LDAP directory
        domainInfos = samba.getDomain()
        # Set domain policy
        samba.setDomainPolicy()
        if not domainInfos:
            logger.error(
                "Can't find sambaDomainName entry in LDAP for domain %s. Please check your SAMBA LDAP configuration."
                % smbconf.getContent("global", "workgroup"))
            return False
        smbconfbasesuffix = smbconf.getContent("global", "ldap suffix")
        if not smbconfbasesuffix:
            logger.error("SAMBA 'ldap suffix' option is not setted.")
            return False
        if ldap.explode_dn(samba.baseDN) != ldap.explode_dn(smbconfbasesuffix):
            logger.error(
                "SAMBA 'ldap suffix' option is not equal to MMC 'baseDN' option."
            )
            return False
        # Check that SAMBA and MMC given OU are in sync
        for option in [
            ("ldap user suffix", "baseUsersDN", samba.baseUsersDN),
            ("ldap group suffix", "baseGroupsDN", samba.baseGroupsDN),
            ("ldap machine suffix", "baseComputersDN", samba.baseComputersDN)
        ]:
            smbconfsuffix = smbconf.getContent("global", option[0])
            if not smbconfsuffix:
                logger.error("SAMBA '" + option[0] + "' option is not setted")
                return False
            # Do a case insensitive comparison of the corresponding MMC / SAMBA options
            if ldap.explode_rdn(smbconfsuffix)[0].lower() != ldap.explode_rdn(
                    option[2])[0].lower():
                logger.error("SAMBA option '" + option[0] +
                             "' is not equal to MMC '" + option[1] +
                             "' option.")
                return False
        # Check that "ldap delete dn" SAMBA option is set to "No"
        smbconfdeletedn = smbconf.isValueTrue(
            smbconf.getContent("global", "ldap delete dn"))
        if smbconfdeletedn == 1:
            logger.error("SAMBA option 'ldap delete dn' must be disabled.")
            return False
        # Check that Domain Computers group exists
        # We need it to put a machine account in the right group when joigning it to the domain
        if not samba.getDomainComputersGroup():
            logger.error(
                "Can't find sambaGroupMapping entry in LDAP corresponding to 'Domain Computers' group. Please check your SAMBA LDAP configuration."
            )
            return False
        # Check that Domain Admins group exists
        if not samba.getDomainAdminsGroup():
            logger.error(
                "Can't find sambaGroupMapping entry in LDAP corresponding to 'Domain Admins' group. Please check your SAMBA LDAP configuration."
            )
            return False
        # Check that Domain Guests group exists
        if not samba.getDomainGuestsGroup():
            logger.error(
                "Can't find sambaGroupMapping entry in LDAP corresponding to 'Domain Guests' group. Please check your SAMBA LDAP configuration."
            )
            return False
        # Check that Domain Users group exists
        if not samba.getDomainUsersGroup():
            logger.error(
                "Can't find sambaGroupMapping entry in LDAP corresponding to 'Domain Users' group. Please check your SAMBA LDAP configuration."
            )
            return False
        # Check that add machine script option is set, and that the given script exist
        addMachineScript = smbconf.getContent("global", "add machine script")
        if not addMachineScript:
            logger.error("SAMBA 'add machine script' option is not set.")
            return False
        else:
            script = addMachineScript.split(" ")[0]
            if not os.path.exists(script):
                logger.error(
                    "SAMBA 'add machine script' option is set to a non existing file: "
                    + script)
                return False
        # Issue a warning if NSCD is running
        if os.path.exists("/var/run/nscd.pid") or os.path.exists(
                "/var/run/.nscd_socket") or os.path.exists("/var/run/nscd"):
            logger.warning(
                "Looks like NSCD is installed on your system. You should not run NSCD on a SAMBA server."
            )
        # Check that os level is set to 255
        oslevel = smbconf.getContent("global", "os level")
        if int(oslevel) < 255:
            logger.debug("Set SAMBA os level to 255.")
            smbconf.setContent("global", "os level", "255")
            smbconf.save()
            reloadSamba()
    try:
        from mmc.plugins.dashboard.manager import DashboardManager
        from mmc.plugins.samba.panel import SambaPanel
        DM = DashboardManager()
        DM.register_panel(SambaPanel("samba"))
    except ImportError:
        pass

    return True
Beispiel #45
0
suffixes = {}
srv1.lastnumchanges = {}
srv2.lastnumchanges = {}
srv1.avgrate = {}
srv2.avgrate = {}
srv1.count = {}
srv2.count = {}
repls = {}
for dn in agmts1to2:
    ents = srv1.search_s(dn, ldap.SCOPE_BASE, "objectclass=*", ["nsDS5ReplicaRoot"])
    ndn = DSAdmin.normalizeDN(dn)
    nrr = DSAdmin.normalizeDN(ents[0].nsDS5ReplicaRoot)
    suffixes[nrr] = dn
    srv1.lastnumchanges[ndn] = 0
    rdns = ldap.explode_dn(dn, 0)
    ndn = DSAdmin.normalizeDN(",".join(rdns[1:]))
    repls[ndn] = ndn
for dn in agmts2to1:
    ents = srv2.search_s(dn, ldap.SCOPE_BASE, "objectclass=*", ["nsDS5ReplicaRoot"])
    ndn = DSAdmin.normalizeDN(dn)
    nrr = DSAdmin.normalizeDN(ents[0].nsDS5ReplicaRoot)
    suffixes[nrr] = dn
    srv2.lastnumchanges[ndn] = 0
    rdns = ldap.explode_dn(dn, 0)
    ndn = DSAdmin.normalizeDN(",".join(rdns[1:]))
    repls[ndn] = ndn

# for dn in repls.keys():
#    for srv in (srv1, srv2):
#        ents = srv.search_s(dn, ldap.SCOPE_BASE)
Beispiel #46
0
                shortname = name[:-len(dn)-2]+" +"
            else:
                shortname = name
            print((" %3d. %s" % (len(dnlist), shortname)))
            dnlist.append(name)

    elif cmd == "cd":
        dn = ""
        dnlist = None

    elif cmd.startswith("cd "):
        arg = cmd[3:]
        if arg == '-':
            lastdn,dn = dn,lastdn
        elif arg == '..':
            dn = ",".join(ldap.explode_dn(dn)[1:])
            dn = str.strip(dn)
        else:
            try:
                i = int(arg)
            except:
                godn = arg
            else:
                if dnlist is None:
                    print ("do an ls first")
                else:
                    godn = dnlist[i]
                lastdn = dn
                dn = godn

    elif cmd == ".":
Beispiel #47
0
        print "ds", ds.title, "ad", ad.title
        retval = False
    return retval

#ds.setLogLevel(0)
#ds.setLogLevel(8192)
#ds.setLogLevel(65536)

subtrees = ((ad,windows_subtree),(ad,active_user_subtree),(ad,deleted_user_subtree),
            (ds, active_user_cont + "," + usersubtree + ',' + suffix),
            (ds, deleted_user_cont + "," + usersubtree + ',' + suffix))

for srv,subtree in subtrees:
    try:
        ent = Entry(subtree)
        rdn = ldap.explode_dn(subtree)[0].split('=')
        if srv == ad:
            ent.setValues('objectclass', ['top', 'container'])
        else:
            ent.setValues('objectclass', ['top', 'nsContainer'])
        ent.setValues(rdn[0], rdn[1])
        srv.add_s(ent)
        print "Created", subtree, "on", str(srv)
    except ldap.ALREADY_EXISTS: pass

replargs['binddn'] = root2
replargs['bindpw'] = rootpw2
replargs['win_subtree'] = adusersubtree + "," + suffix
replargs['ds_subtree'] = usersubtree + ',' + suffix
syncinterval = 30
replargs['interval'] = str(syncinterval)
Beispiel #48
0
def activate():
    """
     this function define if the module "base" can be activated.
     @return: return True if this module can be activate
     @rtype: boolean
    """
    config = SambaConfig("samba")

    if config.disabled:
        logger.info("samba plugin disabled by configuration.")
        return False

    if config.defaultSharesPath:
        if config.defaultSharesPath.endswith("/"):
            logger.error("Trailing / is not allowed in defaultSharesPath")
            return False
        if not os.path.exists(config.defaultSharesPath):
            logger.error("The default shares path '%s' does not exist" % config.defaultSharesPath)
            return False

    for cpath in config.authorizedSharePaths:
        if cpath.endswith("/"):
            logger.error("Trailing / is not allowed in authorizedSharePaths")
            return False
        if not os.path.exists(cpath):
            logger.error("The authorized share path '%s' does not exist" % cpath)
            return False

    # Verify if samba conf file exist
    conf = config.samba_conf_file
    if not os.path.exists(conf):
        logger.error(conf + " does not exist")
        return False

    # validate smb.conf
    smbconf = SambaConf()
    if not smbconf.validate(conf):
        logger.error("SAMBA configuration file is not valid")
        return False

    # For each share, test if it sharePath exists
    for share in getDetailedShares():
        shareName = share[0]
        infos = shareInfo(shareName)
        if infos:
            sharePath = infos["sharePath"]
            if sharePath and not "%" in sharePath and not os.path.exists(sharePath):
                # only show error
                logger.error("The samba share path '%s' does not exist." % sharePath)
        else:
            return False

    try:
        ldapObj = ldapUserGroupControl()
    except ldap.INVALID_CREDENTIALS:
        logger.error("Can't bind to LDAP: invalid credentials.")
        return False

    # Test if the Samba LDAP schema is available in the directory
    try:
        schema = ldapObj.getSchema("sambaSamAccount")
        if len(schema) <= 0:
            logger.error("Samba schema is not included in LDAP directory")
            return False
    except:
        logger.exception("invalid schema")
        return False

    # Verify if init script exist
    init = config.samba_init_script
    if not os.path.exists(init):
        logger.error(init + " does not exist")
        return False

    # If SAMBA is defined as a PDC, make extra checks
    if smbconf.isPdc():
        samba = SambaLDAP()
        # Create SAMBA computers account OU if it doesn't exist
        head, path = samba.baseComputersDN.split(",", 1)
        ouName = head.split("=")[1]
        samba.addOu(ouName, path)
        # Check that a sambaDomainName entry is in LDAP directory
        domainInfos = samba.getDomain()
        # Set domain policy
        samba.setDomainPolicy()
        if not domainInfos:
            logger.error(
                "Can't find sambaDomainName entry in LDAP for domain %s. Please check your SAMBA LDAP configuration."
                % smbconf.getContent("global", "workgroup")
            )
            return False
        smbconfbasesuffix = smbconf.getContent("global", "ldap suffix")
        if not smbconfbasesuffix:
            logger.error("SAMBA 'ldap suffix' option is not setted.")
            return False
        if ldap.explode_dn(samba.baseDN) != ldap.explode_dn(smbconfbasesuffix):
            logger.error("SAMBA 'ldap suffix' option is not equal to MMC 'baseDN' option.")
            return False
        # Check that SAMBA and MMC given OU are in sync
        for option in [
            ("ldap user suffix", "baseUsersDN", samba.baseUsersDN),
            ("ldap group suffix", "baseGroupsDN", samba.baseGroupsDN),
            ("ldap machine suffix", "baseComputersDN", samba.baseComputersDN),
        ]:
            smbconfsuffix = smbconf.getContent("global", option[0])
            if not smbconfsuffix:
                logger.error("SAMBA '" + option[0] + "' option is not setted")
                return False
            # Do a case insensitive comparison of the corresponding MMC / SAMBA options
            if ldap.explode_rdn(smbconfsuffix)[0].lower() != ldap.explode_rdn(option[2])[0].lower():
                logger.error("SAMBA option '" + option[0] + "' is not equal to MMC '" + option[1] + "' option.")
                return False
        # Check that "ldap delete dn" SAMBA option is set to "No"
        smbconfdeletedn = smbconf.isValueTrue(smbconf.getContent("global", "ldap delete dn"))
        if smbconfdeletedn == 1:
            logger.error("SAMBA option 'ldap delete dn' must be disabled.")
            return False
        # Check that Domain Computers group exists
        # We need it to put a machine account in the right group when joigning it to the domain
        if not samba.getDomainComputersGroup():
            logger.error(
                "Can't find sambaGroupMapping entry in LDAP corresponding to 'Domain Computers' group. Please check your SAMBA LDAP configuration."
            )
            return False
        # Check that Domain Admins group exists
        if not samba.getDomainAdminsGroup():
            logger.error(
                "Can't find sambaGroupMapping entry in LDAP corresponding to 'Domain Admins' group. Please check your SAMBA LDAP configuration."
            )
            return False
        # Check that Domain Guests group exists
        if not samba.getDomainGuestsGroup():
            logger.error(
                "Can't find sambaGroupMapping entry in LDAP corresponding to 'Domain Guests' group. Please check your SAMBA LDAP configuration."
            )
            return False
        # Check that Domain Users group exists
        if not samba.getDomainUsersGroup():
            logger.error(
                "Can't find sambaGroupMapping entry in LDAP corresponding to 'Domain Users' group. Please check your SAMBA LDAP configuration."
            )
            return False
        # Check that add machine script option is set, and that the given script exist
        addMachineScript = smbconf.getContent("global", "add machine script")
        if not addMachineScript:
            logger.error("SAMBA 'add machine script' option is not set.")
            return False
        else:
            script = addMachineScript.split(" ")[0]
            if not os.path.exists(script):
                logger.error("SAMBA 'add machine script' option is set to a non existing file: " + script)
                return False
        #  Issue a warning if NSCD is running
        if (
            os.path.exists("/var/run/nscd.pid")
            or os.path.exists("/var/run/.nscd_socket")
            or os.path.exists("/var/run/nscd")
        ):
            logger.warning("Looks like NSCD is installed on your system. You should not run NSCD on a SAMBA server.")
        # Check that os level is set to 255
        oslevel = smbconf.getContent("global", "os level")
        if int(oslevel) < 255:
            logger.debug("Set SAMBA os level to 255.")
            smbconf.setContent("global", "os level", "255")
            smbconf.save()
            reloadSamba()
    try:
        from mmc.plugins.dashboard.manager import DashboardManager
        from mmc.plugins.samba.panel import SambaPanel

        DM = DashboardManager()
        DM.register_panel(SambaPanel("samba"))
    except ImportError:
        pass

    return True
Beispiel #49
0
  def check_single_ldap_setting(self, ldap_config, is_multi_ldap=False):
    self.print_ldap_setting(ldap_config, is_multi_ldap)
    # Basic validation check for hue.ini's ldap parameters [desktop] > [[ldap]]
    err_code = self.check_ldap_params(ldap_config)

    if not err_code:
      # Connect to only one LDAP server given in the hue.ini config
      try:
        connection = ldap_access.get_connection(ldap_config)
      except ldap_access.LdapBindException as err:
        LOG.warn(str(err))
        LOG.info(_(ldap_url_msg))
        LOG.info(_(bind_dn_msg))
        LOG.warn('hints: check bind_dn, bind_password and ldap_url')
        LOG.warn('ldap_url="%s"' % ldap_config.LDAP_URL.get())
        LOG.warn('bind_dn="%s"' % ldap_config.BIND_DN.get())
        err_code = 1
      except:
        typ, value, traceback = sys.exc_info()
        LOG.warn("%s %s" % (typ, value))
        LOG.info(_(ldap_url_msg))
        LOG.info(_(bind_dn_msg))
        LOG.warn('hints: check bind_dn, bind_password and ldap_url')
        LOG.warn('ldap_url="%s"' % ldap_config.LDAP_URL.get())
        LOG.warn('bind_dn="%s"' % ldap_config.BIND_DN.get())
        err_code = 1

      if err_code:
        cfg = ldap_access.get_auth(ldap_config)
        ldapsearch = 'ldapsearch -x -LLL -H {ldap_url} -D "{binddn}" -w "********" -b "" ' \
                     ' -s base'.format(ldap_url=cfg[0], binddn=cfg[1])
        LOG.warn(ldapsearch)
        self.sys_exit(err_code)

      LOG.info('LDAP whoami_s() %s' % (connection.ldap_handle.whoami_s()))
      if ldap_config.TEST_LDAP_USER.get() is not None:
        err_code = self.find_ldapusers(ldap_config, connection)
        if err_code:
          self.sys_exit(err_code)

        if ldap_config.TEST_LDAP_GROUP.get() is not None:
          group_dn = None
          try:
            group_dn = ldap.explode_dn(ldap_config.TEST_LDAP_GROUP.get())
          except:
            group_dn = None

          if group_dn is not None:
            # group DN
            err_code = self.find_users_of_group(ldap_config, connection)
            if err_code:
              self.sys_exit(err_code)
            err_code = self.find_groups_of_group(ldap_config, connection)
            if err_code:
              self.sys_exit(err_code)
          else:
            # group name pattern goes as search attribute
            err_code = self.find_ldapgroups(ldap_config, connection)
            if err_code:
              self.sys_exit(err_code)
        else:
          LOG.info('Now test further by providing test ldap group in CM')
          LOG.info('test_ldap_group=somegroupname')
          LOG.info('test_ldap_group=cn=Administrators,dc=test,dc=com')
      else:
        LOG.info('Now test further by providing test ldap user in CM')
        LOG.info('test_ldap_user=someusername')

    return err_code
Beispiel #50
0
def normalize_dn(dn):
  result = ldap.explode_dn(dn)
  return ','.join(result)
Beispiel #51
0
 def normalizedn(self, dn):
     explodeddn = ldap.explode_dn(dn)
     return string.join(explodeddn,',')
Beispiel #52
0
				shortname = name[:-len(dn)-2]+" +"
			else:
				shortname = name
			print(" %3d. %s" % (len(dnlist), shortname))
			dnlist.append(name)

	elif cmd == "cd":
		dn = ""
		dnlist = None

	elif cmd.startswith("cd "):
		arg = cmd[3:]
		if arg == '-':
			lastdn,dn = dn,lastdn
		elif arg == '..':
			dn = string.join(ldap.explode_dn(dn)[1:], ",")
			dn = dn.strip()
                else:
		        try:
			        i = int(arg)
		        except:
			        godn = arg
                        else:
			        if dnlist is None:
				        print("do an ls first")
                                else:
			                godn = dnlist[i]
		                lastdn = dn
		                dn = godn

	elif cmd == ".":
Beispiel #53
0
        print "title not in sync"
        print "ds", ds.title, "ad", ad.title
        retval = False
    return retval

#ds.setLogLevel(0)
#ds.setLogLevel(8192)
#ds.setLogLevel(65536)

windows_subtree = adusersubtree + "," + suffix
print "Create adusersubtree entry if missing", windows_subtree
try:
    ents = ad.search_s(windows_subtree, ldap.SCOPE_BASE)
except ldap.NO_SUCH_OBJECT:
    ent = Entry(windows_subtree)
    rdn = ldap.explode_dn(windows_subtree)[0].split('=')
    ent.setValues('objectclass', ['top', 'container'])
    ent.setValues(rdn[0], rdn[1])
    ad.add_s(ent)

for ii in xrange(1,6):
    ent = makeADUserEnt(ii)
    try: ad.add_s(ent)
    except ldap.ALREADY_EXISTS:
        print "AD entry", ent.dn, "already exists"
    setWindowsPwd(ad, ent.dn)
    kk = ii % len(userAcctVals)
    mod = []
    for attr, val in userAcctVals[kk].iteritems():
        mod.append((ldap.MOD_REPLACE, attr, str(val)))
    ad.modify_s(ent.dn, mod)
 def explode_dn(self, dn, notypes=0):
     """ Indirection to avoid need for importing ldap elsewhere """
     return ldap.explode_dn(dn, notypes)