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

使用ldapjs创建OU的方法求助:求示例代码及解释

使用ldapjs创建OU的示例代码及说明

创建OU本质是向LDAP服务器添加一个organizationalUnit类型的条目,ldapjs通过client.add()方法实现这一操作,以下是完整示例及细节说明:

完整示例代码

const ldap = require('ldapjs');

// 初始化LDAP客户端
const client = ldap.createClient({
  url: 'ldap://your-ldap-server:389'
});

// 绑定有权限的管理员账号
const adminDn = 'cn=admin,dc=example,dc=com';
const adminPassword = 'your-admin-password';

client.bind(adminDn, adminPassword, (bindErr) => {
  if (bindErr) {
    console.error('身份验证失败:', bindErr);
    return client.unbind();
  }

  // 定义目标OU的DN和属性
  const targetOuDn = 'ou=Sales,dc=example,dc=com';
  const ouEntry = {
    objectClass: ['top', 'organizationalUnit'],
    ou: 'Sales',
    // 可选:添加描述属性
    description: 'Sales Department OU'
  };

  // 执行创建OU操作
  client.add(targetOuDn, ouEntry, (addErr) => {
    if (addErr) {
      console.error('创建OU失败:', addErr);
    } else {
      console.log(`OU ${targetOuDn} 创建成功`);
    }

    // 释放连接
    client.unbind((unbindErr) => {
      if (unbindErr) console.error('连接释放失败:', unbindErr);
    });
  });
});

关键部分解释

  • 客户端初始化:ldap.createClient()传入LDAP服务器地址,默认端口为389(LDAPS协议用636)。
  • 身份验证:必须使用拥有创建OU权限的账号绑定,否则会返回权限不足错误。
  • OU条目属性:
    • objectClass:必须包含top(所有LDAP条目的基类)和organizationalUnit(OU专用对象类),这是LDAP协议的强制要求。
    • ou:值必须与DN中的ou段完全匹配(比如示例中的Sales对应ou=Sales),否则服务器会拒绝请求。
    • 可选属性:可以添加description、seeAlso等自定义或标准属性,丰富OU的元数据。
  • 创建操作:client.add()是核心方法,传入OU的完整DN和条目属性即可发起创建请求。
  • 资源清理:操作完成后必须调用client.unbind()释放连接,避免占用服务器资源。

注意事项

  • 若要创建嵌套OU(如ou=TeamA,ou=Sales,dc=example,dc=com),必须确保父OU(ou=Sales,dc=example,dc=com)已存在,否则会返回"父条目不存在"的错误。
  • 若LDAP服务器启用了TLS,需要在客户端初始化时配置tlsOptions,或直接使用ldaps://协议。

内容的提问来源于stack exchange,提问作者Muhammad Umar Khan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 11:25:34