使用ldap3查询LDAP数据后无法正确导出结果至CSV文件问题求助
问题分析
- 你执行LDAP查询后没有读取返回的
conn.entries结果集,当前代码里写入CSV的data是固定的空列表,仅能输出一行空数据,自然无法得到预期的查询结果 - 没有遍历多条查询结果逐行写入CSV,无法匹配多用户的查询返回
- 直接读取ldap3返回的属性会得到封装后的属性对象,需要取
.value才能拿到实际存储的属性值 - 缺少属性存在性判断逻辑,部分用户如果缺少查询的属性会直接触发脚本报错
修正后的完整代码
from ldap3 import Server, Connection, ALL import csv server = Server('XYZ', get_info=ALL) conn = Connection(server, 'uid=idmsa,ou=People,ou=auth,o=csun', 'XYZ', auto_bind=True) # 执行LDAP查询 conn.search('o=csun', '(&(objectclass=person)(uid>=2147483648))', attributes=['uid', 'employeenumber','csunPrimaryAffiliation']) header = ['uid', 'employeenumber','csunPrimaryAffiliation'] with open('file.csv', 'w', encoding='UTF8', newline='') as f: writer = csv.writer(f) # 写入表头 writer.writerow(header) # 遍历所有查询结果逐行写入 for entry in conn.entries: row = [ entry['uid'].value, entry['employeenumber'].value if 'employeenumber' in entry else '', entry['csunPrimaryAffiliation'].value if 'csunPrimaryAffiliation' in entry else '' ] writer.writerow(row) # 可选:打印结果确认查询正常 print(conn.entries)
补充说明
- 写入CSV时添加
newline=''参数是为了避免Windows系统下CSV文件出现多余空行 - 新增的属性存在性判断可以兼容部分用户缺少对应属性的场景,不会中断脚本执行
- 所有属性都通过
.value取实际存储值,避免写入的内容是ldap3的对象标识
内容的提问来源于stack exchange,提问作者Robin Malhotra
相关产品推荐
相关产品推荐

