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


Python LDIFWriter.unparse方法代码示例

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


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

示例1: generate_ldif_from_list

# 需要导入模块: from ldif import LDIFWriter [as 别名]
# 或者: from ldif.LDIFWriter import unparse [as 别名]
def generate_ldif_from_list(action, array):
    """generate ldif string by array
    Parameters:
        array: a list contains several dicts which contains user or group info.
    """
    if isinstance(array, list):
        output = StringIO()
        w = LDIFWriter(output)
        for a in array:
            if a.has_key('dn'):
                dn = a.pop('dn')
                for k, v in a.iteritems():
                    if not isinstance(v, list):
                        a[k] = [v]

                w.unparse(dn, a)
            else:
                logger.error('the element of ldif does not have "dn": %s', a)


        output.reset()
        r = output.read()
        output.close()

        return r
开发者ID:lls3018,项目名称:mdmi,代码行数:27,代码来源:templates.py

示例2: _entries_to_ldif

# 需要导入模块: from ldif import LDIFWriter [as 别名]
# 或者: from ldif.LDIFWriter import unparse [as 别名]
def _entries_to_ldif(entries):
    """Format LDAP entries as LDIF"""
    io = StringIO()
    writer = LDIFWriter(io)
    for entry in entries:
        writer.unparse(str(entry.dn), dict(entry.raw))
    return io.getvalue()
开发者ID:npmccallum,项目名称:freeipa,代码行数:9,代码来源:tasks.py

示例3: to_ldif

# 需要导入模块: from ldif import LDIFWriter [as 别名]
# 或者: from ldif.LDIFWriter import unparse [as 别名]
    def to_ldif(self, output_file=sys.stdout):
        """Get an LDIF formated output from the LDAP entry.

        :param output_file: Any filehandler object. Default is stdout.

        """
        ldif_writer = LDIFWriter(output_file)
        ldif_writer.unparse(self._dn, dict(self._attrs))
开发者ID:rroemhild,项目名称:pyLDAPHelper,代码行数:10,代码来源:entry.py

示例4: ActiveDirectoryToOpenLdapLDIFConvertor

# 需要导入模块: from ldif import LDIFWriter [as 别名]
# 或者: from ldif.LDIFWriter import unparse [as 别名]
class ActiveDirectoryToOpenLdapLDIFConvertor(LDIFParser):
    objectclassAddsBasedOnDN = { 'CN=ExchangeActiveSyncDevices' : 'exchangeActiveSyncDevices'
                               }

    objectclassChangesBasedOnDN = { 'CN=_Template ': { 'user': 'customActiveDirectoryUserTemplate' },
                                    'CN=_Template_': { 'user': 'customActiveDirectoryUserTemplate' },
                                    'CN=_Template\, ': { 'user': 'customActiveDirectoryUserTemplate' }
                                  }

    objectclassMappings = { 'top' : 'mstop', 'user' : 'customActiveDirectoryUser', 'group' : 'customActiveDirectoryGroup',
                            'contact' : 'customActiveDirectoryContact' }

    attributetypesValuesDuplicates = [ 'dSCorePropagationData' ]

    def __init__(self, input, output):
        LDIFParser.__init__(self, input)
        self.writer = LDIFWriter(output)

    def addObjectclassesBasedOnDN(self, dn, entry):
        for objAdd in self.objectclassAddsBasedOnDN:
            if objAdd.lower() in dn.lower(): # case insensitive match
                if 'objectClass' not in entry.keys():        
                    entry['objectClass'] = [ ]
                entry['objectClass'].append(self.objectclassAddsBasedOnDN[objAdd]);

    def changeObjectclassesBasedOnDN(self, dn, entry):
        if 'objectClass' not in entry.keys():
            return
        for objChange in self.objectclassChangesBasedOnDN:
            if objChange.lower() in dn.lower(): # case insensitive match
                for objSource in self.objectclassChangesBasedOnDN[objChange]:
                    index = 0
                    for objTarget in entry['objectClass']:
                        if objSource == objTarget:
                            entry['objectClass'][index] = self.objectclassChangesBasedOnDN[objChange][objSource]
                        index += 1

    def changeObjectclasses(self, dn, entry):
        if 'objectClass' in entry.keys():        
            index = 0
            for objectclass in entry['objectClass']:
                for objMap in self.objectclassMappings:
                    if objMap == objectclass:
                        entry['objectClass'][index] = self.objectclassMappings[objMap]
                index += 1

    def removeDuplicateAttributeValues(self, dn, entry):
        for attributetype in self.attributetypesValuesDuplicates:
            if attributetype in entry.keys():
                entry[attributetype] = list(set(entry[attributetype]))


    def handle(self, dn, entry):
        self.addObjectclassesBasedOnDN(dn, entry)
        self.changeObjectclassesBasedOnDN(dn, entry)
        self.changeObjectclasses(dn, entry)
        self.removeDuplicateAttributeValues(dn, entry)
        self.writer.unparse(dn, entry)
开发者ID:chenjie4255,项目名称:active-directory-to-openldap,代码行数:60,代码来源:ldif-convertor.py

示例5: StrLdif

# 需要导入模块: from ldif import LDIFWriter [as 别名]
# 或者: from ldif.LDIFWriter import unparse [as 别名]
class StrLdif(object):

    def __init__(self):
        self.sio = StringIO()
        self.ldif_writer = LDIFWriter(self.sio)

    def unparse(self, dn, attrs):
        self.ldif_writer.unparse(dn, attrs)

    def ldif(self):
        return self.sio.getvalue()
开发者ID:Bitlancer,项目名称:strings-datasync,代码行数:13,代码来源:test_mysql2ldif.py

示例6: take_action

# 需要导入模块: from ldif import LDIFWriter [as 别名]
# 或者: from ldif.LDIFWriter import unparse [as 别名]
    def take_action(self, args):
        conn = self.app.conn
        b = self.app.options.b
        context = args.subtree
        groupname = args.groupname

        base_dn = '%s,%s' % (context, b)
        filter = '(cn=%s)' % groupname
        writer = LDIFWriter(sys.stdout)
        for dn, attrs in conn.search_s(base_dn, ldap.SCOPE_SUBTREE, filter):
            writer.unparse(dn, attrs)
开发者ID:hansthen,项目名称:obol,代码行数:13,代码来源:group.py

示例7: DiffWriter

# 需要导入模块: from ldif import LDIFWriter [as 别名]
# 或者: from ldif.LDIFWriter import unparse [as 别名]
class DiffWriter(object):
    """
    A moderately intelligent bridge that interprets adds, changes, and
    deletes between two ldif files and writes them as incremental
    ldifs to an output file.

    Not intended for use outside this module.
    """

    def __init__(self, diff_fil):
        """
        `diff_fil`: the file-like object into which the incremental
        ldifs will be written.
        """
        self.writer = LDIFWriter(diff_fil)
        # Unfortunately we have to maintain this separately from the
        # LDIFWriter since the writer appears to offer no way to
        # delete a full dn.  See handle_delete.
        self.diff_fil = diff_fil

    def handle_add(self, dn_entry):
        """
        Write an incremental ldif to add the supplied dn_entry.
        """
        addition = modlist.addModlist(dn_entry.entry)
        self.writer.unparse(dn_entry.dn, addition)

    def handle_change(self, old_dn_entry, new_dn_entry):
        """
        Write an incremental ldif to modify the old entry into the new
        entry.

        If old_dn_entry and new_dn_entry are identical, acts as a
        no-op.

        Raises an exception if the old and new entries don't have the
        same dn.
        """
        if old_dn_entry.dn != new_dn_entry.dn:
            raise NonMatchingDnException("Old and new dn'ss must be the same.")
        changes = modlist.modifyModlist(old_dn_entry.entry, new_dn_entry.entry)
        if changes:
            self.writer.unparse(old_dn_entry.dn, changes)

    def handle_delete(self, dn_entry):
        """
        Write the incremental ldif to delete the dn of the supplied
        entry.
        """
        self.diff_fil.write("dn: %s\n" % dn_entry.dn)
        self.diff_fil.write('changetype: delete\n')
        self.diff_fil.write('\n')
开发者ID:Bitlancer,项目名称:strings-datasync,代码行数:54,代码来源:ldiff.py

示例8: ldap

# 需要导入模块: from ldif import LDIFWriter [as 别名]
# 或者: from ldif.LDIFWriter import unparse [as 别名]
 def ldap(self, command, attrs):
     self.logger.debug('received command %s %s', command, attrs)
     if command == 'SEARCH':
         out = StringIO()
         ldif_writer = LDIFWriter(out)
         qs = get_user_model().objects.all()
         if attrs['filter'] != '(objectClass=*)':
             m = re.match(r'\((\w*)=(.*)\)', attrs['filter'])
             if not m:
                 print 'RESULT'
                 print 'code: 1'
                 print 'info: invalid filter'
                 print
                 return
             for user_attribute, ldap_attribute in MAPPING.iteritems():
                 if ldap_attribute == m.group(1):
                     break
             else:
                 print 'RESULT'
                 print 'code: 1'
                 print 'info: unknown attribute in filter'
                 print
                 return
             value = m.group(2)
             if value.endswith('*') and value.startswith('*'):
                 user_attribute += '__icontains'
                 value = value[1:-1]
             elif value.endswith('*'):
                 user_attribute += '__istartswith'
                 value = value[:-1]
             elif value.startswith('*'):
                 user_attribute += '__iendswith'
                 value = value[1:]
             else:
                 user_attribute += '__iexact'
             value = unescape_filter_chars(value)
             qs = qs.filter(**{user_attribute: value.decode('utf-8')})
         for user in qs:
             o = {}
             for user_attribute, ldap_attribute in MAPPING.iteritems():
                 o[ldap_attribute] = [unicode(getattr(user, user_attribute)).encode('utf-8')]
             o['objectClass'] = ['inetOrgPerson']
             dn = 'uid=%s,%s' % (escape_dn_chars(o['uid'][0]), attrs['suffix'])
             self.logger.debug(u'sending entry %s %s', dn, o)
             ldif_writer.unparse(dn, o)
         print out.getvalue(),
         out.close()
     print 'RESULT'
     print 'code: 0'
     print 'info: RockNRoll'
     print
开发者ID:josuebrunel,项目名称:authentic2,代码行数:53,代码来源:slapd-shell.py

示例9: __init__

# 需要导入模块: from ldif import LDIFWriter [as 别名]
# 或者: from ldif.LDIFWriter import unparse [as 别名]
class globals:
    def __init__(self):
        self.global_objs = {}
        self.ldif = LDIFWriter(sys.stdout)

    def add_attr(self, dn, attname, vals):
        if dn not in self.global_objs:
           self.global_objs[dn] = {}
        self.global_objs[dn][attname] = vals

    def print_all(self):
        for dn, obj in self.global_objs.items():
           self.ldif.unparse(dn, obj)
           continue
        self.global_objs = {}
开发者ID:DavidMulder,项目名称:samba,代码行数:17,代码来源:repl_cleartext_pwd.py

示例10: ActiveDirectoryDefaultUserSetup

# 需要导入模块: from ldif import LDIFWriter [as 别名]
# 或者: from ldif.LDIFWriter import unparse [as 别名]
class ActiveDirectoryDefaultUserSetup(LDIFParser):
    password = ""

    def __init__(self, input, output, password):
        LDIFParser.__init__(self, input)
        self.writer = LDIFWriter(output)
        self.password = password

    def setUserDefaultPassword(self, dn, entry):
        if 'objectClass' not in entry.keys():
            return
        if 'user' in entry['objectClass']:
            entry['userPassword'] = [ self.password ]


    def handle(self, dn, entry):
        self.setUserDefaultPassword(dn, entry)
        self.writer.unparse(dn, entry)
开发者ID:chenjie4255,项目名称:active-directory-to-openldap,代码行数:20,代码来源:add-default-user-password.py

示例11: generate_ldif

# 需要导入模块: from ldif import LDIFWriter [as 别名]
# 或者: from ldif.LDIFWriter import unparse [as 别名]
def generate_ldif(action, use_template=False, sync_source='MDM', **kwargs):
    """generate ldif string by kwargs or from template.
    Parameters:
        use_template: boolean,'CREATESESSION' and 'CLOSESESSION' should use template, others False.
        sync_source: 'MDM' or 'Directory'
        **kwargs: all items of dict.
    """
    output = StringIO()
    w = LDIFWriter(output)
    if use_template:
        if not templates.has_key(action):
            return ""

        d = templates[action]
        for i in d:
            w.unparse(*i)

        output.reset()
        r = output.read()
        output.close()

        if sync_source:
            r = r.format(sync_source=sync_source, current_time=datetime.today().strftime("%Y%m%d%H%M%SZ"), **kwargs)
        else:
            r = r.format(**kwargs)

        return r
    else:
        if not kwargs.has_key('dn'):
            output.close()
            return ""
        dn = kwargs.pop('dn')
        for k, v in kwargs.iteritems():
            if not isinstance(v, list):
                kwargs[k] = [v]

        w.unparse(dn, kwargs)

        output.reset()
        r = output.read()
        output.close()

        return r
开发者ID:lls3018,项目名称:mdmi,代码行数:45,代码来源:templates.py

示例12: fixLdapBindDN

# 需要导入模块: from ldif import LDIFWriter [as 别名]
# 或者: from ldif.LDIFWriter import unparse [as 别名]
    def fixLdapBindDN(self):
        
        applience_fn = os.path.join(self.backupDir, 'ldif/appliance.ldif')
        parser = MyLDIF(open(applience_fn, 'rb'), None, True)
        parser.parse()
        tmp_fn = '/tmp/appliance.ldif'
        processed_fp = open(tmp_fn, 'w')
        ldif_writer = LDIFWriter(processed_fp)
        
        for dn, entry in parser.dn_entry:
            if 'oxIDPAuthentication' in entry:
                tmp_json = json.loads(entry['oxIDPAuthentication'][0])
                tmp_config = json.loads(tmp_json['config'])
                tmp_config['bindDN'] = 'cn=Directory Manager'
                tmp_json['config'] = json.dumps(tmp_config)
                entry['oxIDPAuthentication'] = [json.dumps(tmp_json)]

            ldif_writer.unparse(dn, entry)
        
        processed_fp.close()
        os.system('cp {0} {1}'.format(tmp_fn, applience_fn))
        os.remove(tmp_fn)
        
        
        oxtrust_config_fn = os.path.join(self.backupDir, 'ldif/oxtrust_config.ldif')
        parser = MyLDIF(open(oxtrust_config_fn, 'rb'), None, True)
        parser.parse()
        tmp_fn = '/tmp/oxtrust_config.ldif'
        processed_fp = open(tmp_fn, 'w')
        ldif_writer = LDIFWriter(processed_fp)
        
        for dn, entry in parser.dn_entry:
            if 'oxTrustConfCacheRefresh' in entry:
                tmp_json = json.loads(entry['oxTrustConfCacheRefresh'][0])
                tmp_json['inumConfig']['bindDN'] = 'cn=Directory Manager'
                entry['oxTrustConfCacheRefresh'] = [json.dumps(tmp_json)]

            ldif_writer.unparse(dn, entry)
        
        processed_fp.close()
        os.system('cp {0} {1}'.format(tmp_fn, oxtrust_config_fn))
        os.remove(tmp_fn)
开发者ID:GluuFederation,项目名称:community-edition-setup,代码行数:44,代码来源:export3031.py

示例13: MyLDIF

# 需要导入模块: from ldif import LDIFWriter [as 别名]
# 或者: from ldif.LDIFWriter import unparse [as 别名]
    class MyLDIF(LDIFParser):
        def __init__(self,input,output):
            LDIFParser.__init__(self,input)
            self.writer = LDIFWriter(output)

       # Encode special dn-specific backup logic here.
        def handle(self,dn,entry):
            if dn in make_modify:
                if not 'memberUid' in entry:
                    # No members in this group, discard
                    return

                members = entry['memberUid']
                self.writer.unparse(dn,[(ldap.MOD_REPLACE,'memberUid',members)])
                return
            elif dn in remove:
                return
            elif dn == None:
                return
            else:
                self.writer.unparse(dn,entry)
开发者ID:PeterJCLaw,项目名称:server-backup,代码行数:23,代码来源:backup.py

示例14: FixLDIF

# 需要导入模块: from ldif import LDIFWriter [as 别名]
# 或者: from ldif.LDIFWriter import unparse [as 别名]
class FixLDIF(LDIFParser):
    def __init__(self, input, output):
        LDIFParser.__init__(self, input)
        self.writer = LDIFWriter(output)
    def handle(self, dn, entry):
        dn = self.fix_dn(dn)
        self.fix_entry(entry)
        self.fix_objectclass(entry['objectclass'])
        self.writer.unparse(dn, entry)
    def fix_dn(self, dn):
        head = dn.split(',', 1)[0]
        return head + ',' + basedn
    def fix_entry(self, entry):
        for value in ignore_attribute:
            if value in entry:
                del entry[value]
        for target, source in copy_attribute:
            entry[target] = entry[source]
    def fix_objectclass(self, objectclass):
        for value in ignore_objectclass:
            if value in objectclass:
                objectclass.remove(value)
开发者ID:bhramoss,项目名称:code,代码行数:24,代码来源:recipe-476224.py

示例15: processLDIF

# 需要导入模块: from ldif import LDIFWriter [as 别名]
# 或者: from ldif.LDIFWriter import unparse [as 别名]
def processLDIF(backupFolder, newFolder):
    logging.info('Processing the LDIF data')
    current_ldif = os.path.join(newFolder, 'current.ldif')
    currentDNs = getDns(current_ldif)

    processed_ldif = open(os.path.join(newFolder, 'processed.ldif'), 'w')
    ldif_writer = LDIFWriter(processed_ldif)

    ignoreList = ['objectClass', 'ou', 'oxAuthJwks', 'oxAuthConfWebKeys']
    old_dn_map = getOldEntryMap(backupFolder)

    multivalueAttrs = ['oxTrustEmail', 'oxTrustPhoneValue', 'oxTrustImsValue',
                       'oxTrustPhotos', 'oxTrustAddresses', 'oxTrustRole',
                       'oxTrustEntitlements', 'oxTrustx509Certificate']
    # Rewriting all the new DNs in the new installation to ldif file
    for dn in currentDNs:
        new_entry = getEntry(current_ldif, dn)
        if dn not in old_dn_map.keys():
            #  Write directly to the file if there is no matching old DN data
            ldif_writer.unparse(dn, new_entry)
            continue

        old_entry = getEntry(os.path.join(backupFolder, old_dn_map[dn]), dn)
        for attr in old_entry.keys():
            if attr in ignoreList:
                continue

            if attr not in new_entry:
                new_entry[attr] = old_entry[attr]
            elif old_entry[attr] != new_entry[attr]:
                if len(old_entry[attr]) == 1:
                    try:
                        old_json = json.loads(old_entry[attr][0])
                        new_json = json.loads(new_entry[attr][0])
                        new_json = merge(new_json, old_json)
                        new_entry[attr] = [json.dumps(new_json)]
                    except:
                        new_entry[attr] = old_entry[attr]
                        logging.debug("Keeping old value for %s", attr)
                else:
                    new_entry[attr] = old_entry[attr]
                    logging.debug("Keep multiple old values for %s", attr)
        ldif_writer.unparse(dn, new_entry)

    # Pick all the left out DNs from the old DN map and write them to the LDIF
    for dn in sorted(old_dn_map, key=len):
        if dn in currentDNs:
            continue  # Already processed

        entry = getEntry(os.path.join(backupFolder, old_dn_map[dn]), dn)

        for attr in entry.keys():
            if attr not in multivalueAttrs:
                continue  # skip conversion

            attr_values = []
            for val in entry[attr]:
                json_value = None
                try:
                    json_value = json.loads(val)
                    if type(json_value) is list:
                        attr_values.extend([json.dumps(v) for v in json_value])
                except:
                    loggin.debug('Cannot parse multival %s in DN %s', attr, dn)
                    attr_values.append(val)
            entry[attr] = attr_values

        ldif_writer.unparse(dn, entry)

    # Finally
    processed_ldif.close()
开发者ID:GluuFederation,项目名称:community-edition-setup,代码行数:73,代码来源:import244.py


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