本文整理汇总了Python中ldif.LDIFWriter类的典型用法代码示例。如果您正苦于以下问题:Python LDIFWriter类的具体用法?Python LDIFWriter怎么用?Python LDIFWriter使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了LDIFWriter类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: generate_ldif_from_list
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
示例2: _entries_to_ldif
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()
示例3: to_ldif
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))
示例4: ActiveDirectoryToOpenLdapLDIFConvertor
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)
示例5: StrLdif
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()
示例6: take_action
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)
示例7: DiffWriter
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')
示例8: ldap
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
示例9: __init__
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 = {}
示例10: ActiveDirectoryDefaultUserSetup
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)
示例11: __init__
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
示例12: generate_ldif
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
示例13: MyLDIF
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)
示例14: FixLDIF
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)
示例15: fixLdapBindDN
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)