有点乱这个东西
大致意思是,在ubuntu上安装ldap,通过ldapadmin管理ldap,调用linux环境下c语言api实现对ldap条目的crud。
已经搭建的环境下,并且创建并添加了一些条目。
初始化、绑定、对要添加的数据处理、添加、断开LDAP连接。
#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";
char* sn = "Doe";
char* userPassword = "666666";
char* mail = "john.doe@example.com";
char* uid = "88888888";
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", attributes };
LDAPMod sn_mod = { LDAP_MOD_ADD, "sn", attributes + 1 };
LDAPMod userPassword_mod = { LDAP_MOD_ADD, "userPassword", attributes + 2};
LDAPMod mail_mod = { LDAP_MOD_ADD, "mail", attributes + 3 };
LDAPMod uid_mod = {LDAP_MOD_ADD, "uid", attributes + 4};
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的链接库
如 gcc test.cpp -o test -lldap -llber
运行(./test)结果