这对我来说实际上看起来像一个
LDIF文件.
python-ldap库有一个纯Python LDIF处理库,如果你的文件在LDIF中拥有一些令人讨厌的陷阱,可以提供帮助,例如: Base64编码值,条目折叠等.
您可以像这样使用它:
import csv
import ldif
class ParseRecords(ldif.LDIFParser):
def __init__(self, csv_writer):
self.csv_writer = csv_writer
def handle(self, dn, entry):
self.csv_writer.writerow([entry['LoginId'], entry['mail']])
with open('/path/to/large_file') as input, with open('output_file', 'wb') as output:
csv_writer = csv.writer(output)
csv_writer.writerow(['LoginId', 'Mail'])
ParseRecords(input, csv_writer).parse()
编辑
因此,要从实时LDAP目录中提取,使用python-ldap库,您可能希望执行以下操作:
import csv
import ldap
con = ldap.initialize('ldap://server.fqdn.system.edu')
# if you're LDAP directory requires authentication
# con.bind_s(username, password)
try:
with open('output_file', 'wb') as output:
csv_writer = csv.writer(output)
csv_writer.writerow(['LoginId', 'Mail'])
for dn, attrs in con.search_s('ou=Students,o=system.edu,o=system', ldap.SCOPE_SUBTREE, attrlist = ['LoginId','mail']:
csv_writer.writerow([attrs['LoginId'], attrs['mail']])
finally:
# even if you don't have credentials, it's usually good to unbind
con.unbind_s()
请注意,在上面的示例中,我完全跳过提供过滤器,您可能希望在生产中执行此过滤器. LDAP中的过滤器类似于SQL语句中的WHERE子句;它限制返回的对象. Microsoft actually has a good guide on LDAP filters. LDAP过滤器的规范参考是RFC 4515.
类似地,如果在应用适当的过滤器之后可能存在数千个条目,您可能需要查看LDAP paging control,尽管使用它会再次使示例更复杂.希望这足以让你开始,但如果有任何问题,请随时提出或打开一个新问题.
祝好运.