#include <stdio.h>
#include <cstdlib>
//#include <iostream>
//using namespace std;
extern "C"
{
#define LDAP_DEPRECATED 1
#include <ldap.h>
#include <lber.h>
}
#define HOST "192.168.99.99"
#define PORT 389
#define WHO "cn=admin,dc=nodomain"
#define PASSWD "secret"
#define FIND_DN "dc=nodomain"
bool auth()
{
LDAP *ld;
//BerElement *ber;
char *a;
char **vals;
int i, rc;
int i_version = LDAP_VERSION3;
ld = ldap_init(HOST, PORT);
if(ld == NULL)
{
perror("ldap_init");
return false;
}
printf("ldap_init success\n");
ldap_set_option(ld, LDAP_OPT_PROTOCOL_VERSION, &i_version);
ldap_set_option(ld, LDAP_OPT_REFERRALS, LDAP_OPT_ON);
rc = ldap_simple_bind_s(ld, WHO, PASSWD);
if(rc != LDAP_SUCCESS)
{
fprintf(stderr, "ldap_simple_bind_s: rc: %d, %s\n", rc, ldap_err2string(rc));
return false;
}
printf("ldap_simple_bind_s success\n");
// 创建用户的属性
//dn: uid=690106015133,ou=Employees,ou=People,dc=upm,dc=nodomain
const char *dn = "uid=888888,ou=Employees,ou=People,dc=upm,dc=nodomain";
char* object_class[] = {"person", "inetOrgPerson", NULL};
char* cn[] = {"John Doe", NULL};
char* sn[] = {"Doe", NULL};
char* userPassword[] = {"666666", NULL};
char* mail[] = {"john.doe@example.com", NULL};
//char* uid[] = {"88888888", NULL};
//char* attributes[] = {"cn", cn, "sn", sn, "userPassword", userPassword, "mail", mail, "uid", uid, NULL};
LDAPMod object_class_mod = { LDAP_MOD_ADD, "objectClass", object_class };
LDAPMod cn_mod = { LDAP_MOD_ADD, "cn", cn };
LDAPMod sn_mod = { LDAP_MOD_ADD, "sn", sn };
LDAPMod userPassword_mod = { LDAP_MOD_ADD, "userPassword", userPassword};
LDAPMod mail_mod = { LDAP_MOD_ADD, "mail", mail };
//LDAPMod uid_mod = {LDAP_MOD_ADD, "uid", uid};
LDAPMod* mods[] = { &object_class_mod, &cn_mod, &sn_mod, &userPassword_mod, &mail_mod, /*&uid_mod,*/ NULL };
rc = ldap_add_ext_s(ld, dn, mods, NULL, NULL);
if(rc == LDAP_SUCCESS)
{
// std::cout << "LDAP add operation succeeded." << std::endl;
printf("成功添加\n");
}
else
{
// std::cout << "LDAP add operation failed: " << ldap_err2string(rc) << std::endl;
printf("添加失败\n");
}
// 断开 LDAP 连接
ldap_unbind_ext_s(ld, NULL, NULL);
return true;
}
int main()
{
auth();
return 0;
}
简单说一下,上一篇博客是可以添加条目的,但是存在一些问题,属性与属性值没有一一对应。更重要的原因是对LDAP的 LDAPMod数据类型不熟悉。其中需要注意的是在结尾都需要用NULL结尾
所以后面干脆直接重新写死。
后续再慢慢改进~