You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python检索LDAP转储文件中关联的特定OU数据

Python处理大体积LDAP转储文件:提取指定OU及关联OU的属性值

核心思路

  1. 按空行分割LDAP转储文件中的条目组,逐组解析避免一次性加载大文件占用过多内存
  2. 解析每个条目组的DN(识别目标OU)和属性键值对
  3. 先收集所有OU的属性数据,再根据目标OU关联提取所需的关联OU属性

代码实现

def parse_ldap_dump(file_path):
    entries = []
    current_entry = {}
    current_attr = None

    with open(file_path, 'r', encoding='utf-8') as f:
        for line in f:
            line = line.strip()
            # 空行表示当前条目结束
            if not line:
                if current_entry:
                    entries.append(current_entry)
                    current_entry = {}
                current_attr = None
                continue
            
            # 解析DN行(以dn:开头)
            if line.lower().startswith('dn:'):
                dn = line[3:].strip()
                current_entry['dn'] = dn
                # 从DN中提取OU名称
                ou_parts = [part.split('=')[1] for part in dn.split(',') if part.lower().startswith('ou=')]
                current_entry['ou'] = ou_parts[0] if ou_parts else None
                continue
            
            # 解析属性行,处理多行属性值(缩进的行属于上一个属性)
            if line.startswith((' ', '\t')):
                if current_attr and current_attr in current_entry:
                    current_entry[current_attr] += '\n' + line.strip()
                continue
            
            # 普通属性行(键: 值格式)
            if ': ' in line:
                key, value = line.split(': ', 1)
                current_attr = key.strip()
                current_entry[current_attr] = value.strip()
    
    # 处理最后一个条目
    if current_entry:
        entries.append(current_entry)
    
    return entries

def extract_target_ou_data(entries, target_ou, related_ous):
    # 先构建OU到属性的映射
    ou_map = {entry['ou']: entry for entry in entries if 'ou' in entry}
    
    result = {}
    # 获取目标OU的直接属性
    if target_ou in ou_map:
        target_entry = ou_map[target_ou]
        result['target_ou'] = {
            'name': target_ou,
            'attributes': {k: v for k, v in target_entry.items() if k not in ['dn', 'ou']}
        }
    
    # 获取关联OU的属性
    result['related_ous'] = []
    for ou in related_ous:
        if ou in ou_map:
            related_entry = ou_map[ou]
            result['related_ous'].append({
                'name': ou,
                'attributes': {k: v for k, v in related_entry.items() if k not in ['dn', 'ou']}
            })
    
    return result

if __name__ == '__main__':
    # 配置参数
    LDAP_DUMP_PATH = 'your_ldap_dump.txt'
    TARGET_OU = 'chuckSudo'
    RELATED_OUS = ['upperusers', 'upperhosts']
    
    # 解析文件
    ldap_entries = parse_ldap_dump(LDAP_DUMP_PATH)
    # 提取目标数据
    output_data = extract_target_ou_data(ldap_entries, TARGET_OU, RELATED_OUS)
    
    # 格式化输出(JSON格式)
    import json
    print(json.dumps(output_data, indent=2, ensure_ascii=False))

代码说明

  • parse_ldap_dump函数:逐行读取文件,按空行分割条目,处理DN行提取OU名称,同时支持多行属性值(LDAP转储中属性值换行时会缩进)
  • extract_target_ou_data函数:先建立所有OU的属性映射,再快速提取目标OU和关联OU的属性,避免多次遍历
  • 大文件处理:逐行读取而非一次性加载,内存占用可控,适合1万行以上的文件

自定义输出格式

如果需要纯文本格式,可替换输出部分代码:

# 自定义文本格式输出
print(f"=== 目标OU: {TARGET_OU} ===")
if 'target_ou' in output_data:
    for attr, value in output_data['target_ou']['attributes'].items():
        print(f"{attr}: {value}")

print("\n=== 关联OU ===")
for related in output_data['related_ous']:
    print(f"\n--- {related['name']} ---")
    for attr, value in related['attributes'].items():
        print(f"{attr}: {value}")

注意事项

  • 确保LDAP转储文件的编码正确(代码中用utf-8,若文件是其他编码需调整)
  • 若DN格式特殊,需修改ou_parts的提取逻辑适配你的文件格式
  • 支持属性值包含换行的情况(比如多行的sudoCommand)

内容的提问来源于stack exchange,提问作者M_66

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 17:17:32