Archives for : ldap

ldapsearch limit returned results

Problem

You want to perform an ldap search but only receive a limited number of records in return.



Solution

Use -z # to restrict the number of records returned.



Example


Search and return only 5 records.


ldapsearch -x -z 5 -v-D"cn=Manager,dc=demo,dc=net"-w secret
-b"dc=demo,dc=net" "(lastlogin>=99999999)"



Reference

[tags], LDAP Training School[/tags]



ldapsearch greater than

Problem

You want to search for a field greater than a value, in your LDAP search.



Solution

To search for a field with a value greater than a given figure, we use >=. If you try to just use > it chucks out an error.



Example


This is how to perform a greater than LDAP search.


ldapsearch -x -v-D"cn=Manager,dc=demo,dc=net"-w secret
-b"dc=demo,dc=net" "(lastlogin>=99999999)"



Reference

[tags]ldapsearch syntax, openldap ldapsearch, LDAP Training School[/tags]



LDAP LDIF Perl search script

Problem

You want to search an LDIF file for a given dn, or pattern.



Solution

Multi-line pattern search and output – useful for LDIFs! 😉

Written in Perl – see example tab.



Example


Replace pattern to a given name, etc and filename to LDIF output file.

perl -ane '$/="dn" ;

print,"\n\n" if($_ =~/pattern/);' filename

For example:


$ cat user.ldif
dn: cn=user0,dc=subdiv,dc=demo,dc=net
objectClass: person
sn: User
cn: user0
userPassword: today321

dn: cn=user1,dc=subdiv,dc=demo,dc=net
objectClass: person
sn: User
cn: user1
userPassword: today321

$ perl -ane '$/="dn" ;
print,"nn" if($_ =~/user1/);' user.ldif

: cn=user1,dc=subdiv,dc=demo,dc=net
objectClass: person
sn: User
cn: user1
userPassword: today321



Reference

[tags]LDAP LDIF Search, LDAP LDIF extraction, LDAP Training School[/tags]



Modify LDAP records with JNDI

Problem

Need to modify an LDAP record with JNDI, the Java Naming Directory Interface.

Following on from using java to perform LDAP searches, here is a quick demo on modifying records.



Solution

Here I’m using java to modify John Doe’s record, changing the givenname entry to John A.

As you’ll notice all values are hard coded (such as hostname, port, password, etc). These could be read in from a config file, or passed in through command line arguments.



Example



$ cat chLdapDetails.java
import java.util.*;
import java.io.*;
import javax.naming.*;
import javax.naming.directory.*;
import javax.naming.ldap.*;

public class chLdapDetails {

public static void main(String argv[]) {

String url="ldap://127.0.0.1:389";
Hashtable env=new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL,url);
env.put(Context.SECURITY_AUTHENTICATION,"simple");
env.put(Context.SECURITY_PRINCIPAL,
"cn=Manager,dc=demo,dc=net");
env.put(Context.SECURITY_CREDENTIALS,"secret");

try {

DirContext ctx=new InitialDirContext(env);
ModificationItem[] mods = new ModificationItem[1];
mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
new BasicAttribute("givenname","John A"));
ctx.modifyAttributes("cn=jdoe,dc=demo,dc=net", mods);
ctx.close();

} catch(NamingException ne) { System.err.println(ne.toString()); }

}
}

Heres a run through:


$ java getLdapDetails Doe
John, Doe - [email protected]

$ java chLdapDetails
$ java getLdapDetails Doe
John A, Doe - [email protected]



Reference

[tags]LDAP updates JNDI, JNDI LDAP, JNDI, LDAP Training School[/tags]



ldapsearch logical NOT

Problem

You want to perform an LDAP search, matching entries which do not match certain criteria.



Solution

To perform a logical NOT we just use the exclamation mark ! – see example.



Example


This is how to perform a logical OR LDAP search.


ldapsearch -x -v-D"cn=Manager,dc=demo,dc=net"-w secret
-b"dc=demo,dc=net" "(!(sn=Doe))"



Reference

[tags]ldapsearch syntax, openldap ldapsearch, LDAP Training School[/tags]



ldapsearch logical AND

Problem

You want to match more than one field, in your LDAP search.



Solution

To match more than one field we use the ampersand – “&” with ldapsearch.



Example


This is how to perform a logical AND LDAP search.


ldapsearch -x -v-D"cn=Manager,dc=demo,dc=net"-w secret
-b"dc=demo,dc=net" "(&(givenname=John)(sn=Smith))"



Reference

[tags]ldapsearch syntax, openldap ldapsearch, LDAP Training School[/tags]



ldapsearch with logical OR

Problem

You want to match more one or another pattern, in your LDAP search.



Solution

To match more one pattern or another we use the pipe symbol “|” .



Example


This is how to perform a logical OR LDAP search.


ldapsearch -x -v-D"cn=Manager,dc=demo,dc=net"-w secret
-b"dc=demo,dc=net" "(|(sn=Doe)(sn=Smith))"



Reference

[tags]ldapsearch syntax, openldap ldapsearch, LDAP Training School[/tags]



Deleting LDAP Record

Problem

You want to delete a LDAP entry.



Solution

In this example, we just use ldapdelete from the command line.

Remember to take a backup. ldapsearch with -L



Example


Here is an example of deleting a record in LDAP:


ldapdelete -v -D'cn=Manager..' -w ${passwd}
-h ${host} -p ${port}<<EOT
cn=….
EOT

Effectively – you just need to supply the full DN. Also be aware you need to delete the lowest branch first, for example:

uid=….
sales=…,uid=….

You need to delete sales first, then uid.



Reference

[tags]ldapdelete, LDAP Training School[/tags]



Modify LDAP record entry

Problem

You want to modify or change a record in LDAP.

Supplanting one value with another.



Solution

Use ldapmodify from the command line.

Again take a backup with -L – just to be sure. 🙂



Example


Here is an example of modifying a record in LDAP, when you need to modify an entry to an existing record:


ldapmodify -x -v-D”cn=Manager,dc=demo,dc=net”-w secret<<EOT
dn: cn=jdoe,dc=demo,dc=net
changetype: modify
replace: mail
mail: [email protected]
EOT



Reference

[tags]ldapmodify, modify ldap record, LDAP Training School[/tags]



Beginning ldap – modify a record

Problem

You want to modify an LDAP record.

For example change telephone number, address, etc.



Solution

Use ldapmodify from command line. I might seem daunting to start with, but it is the best way.

Plus you should perform a search with -L option, to take a backup to file.



Example


Here is an example of modifying a record in LDAP, when you need to add an entry to an existing record:


ldapmodify -x -v-D”cn=Manager,dc=demo,dc=net”-w secret<<EOT
dn: cn=jdoe,dc=demo,dc=net
changetype: modify
add: mail
mail: mail: [email protected]
EOT

Here we are adding the mail field and value.



Reference

[tags]ldapmodify, adding field to ldap record, LDAP Training School[/tags]



Adding LDAP record

Problem

You want to add an LDAP record. Effectively create a record.



Solution

To add a record to LDAP, you simply run an ldapmodify with the -a flag.



Example



ldapmodify -x -a -v-D”cn=Manager,dc=demo,dc=net”-w secret < ldifFile

Where ldifFile is a file either hand crafted or generated with ldapsearch -L.



Reference

[tags]ldapadd, ldapmodify, LDAP Training School[/tags]



LDAP to SQL Perl code

Problem

Whilst working on the automatic production of web statistics – came across the following problem:

“How do I get relational data from an Hierarchical structure?”



Solution

It didn’t take long to realize – I’d have to use PHP to talk to LDAP, pull off records & upload into a series of tables, using the cn as primary key. Which then could be queried relationally. Pulling off large, queries and repeatedly transcending LDAP trees is pretty slow – so I built my LDAP to SQL engine, by flattening dns into table names. Then used PHP scripts to query produce
daily snap shots.

This is the Perl port of the PHP version. Requires some setting up on db side, but invaluable once implemented.

Please leave a comment if you want help with this.



Example


Perl LDAP to SQL
[freeware]

UNIX

Traverses LDAP trees and spits out SQL.


Windows



Reference

[tags]LDAP, SQL, Perl, PHP[/tags]



ldapsearch syntax part three

Problem

Looking for a given user, searching on 2 fields – first name and surname.



Solution

Here is an example of searching against 2 fields, effectively a logical AND.



Example


Searching on two fields and returning those fields, plus email.


ldapsearch -x -v-D"cn=Manager,dc=demo,dc=net"-w secret
-b'dc=demo,dc=net' -s sub '(&(givenname=John)(sn=Doe))'
givenname sn mail



Reference

[tags]ldapsearch syntax, openldap ldapsearch, LDAP Training School[/tags]



ldapsearch syntax part two

Problem

Looking for a given user, searching my first name.



Solution

ldapsearch can match on any field, within the LDAP record and perform wildcard matches.



Example


Here are some more examples:

ldapsearch -L -x -v -D’cn=Manager,dc=demo,dc=net’ -w secret -b’dc=demo,dc=net’ -s sub ‘givenname=*' givenname sn mail

Basic LDAP syntax demo part2



Reference

[tags]ldapsearch syntax, openldap ldapsearch, LDAP Training School[/tags]



Java JNDI talk to LDAP

Problem

You want to talk to LDAP from Java.



Solution

Java as well as Perl, PHP and plain old Shell have APIs to be able to talk to LDAP.

The Java API is probably most complex one to use – I have provided some demos on how to use the others on this site.

More will be added in time.



Example


Here is a full example of using Java's JNDI to talk to LDAP, performing a search and supplying results:

import java.util.*;
import java.io.*;
import javax.naming.*;
import javax.naming.directory.*;
import javax.naming.ldap.*;

public class getLdapDetails {

public static void main(String argv[]) {

String url="ldap://127.0.0.1:389";
Hashtable env=new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL,url);
env.put(Context.SECURITY_AUTHENTICATION,"simple");
env.put(Context.SECURITY_PRINCIPAL,
"cn=Manager,dc=demo,dc=net");
env.put(Context.SECURITY_CREDENTIALS,"secret");

try {

DirContext ctx=new InitialDirContext(env);

String[] attrIDs = { "givenname","sn","mail" } ;
Attributes matchAttrs = new BasicAttributes(true); //ignore case
matchAttrs.put(new BasicAttribute("sn",argv[0]));
NamingEnumeration myenum =
ctx.search("dc=demo,dc=net",matchAttrs, attrIDs);

while( myenum.hasMore()) {

String PersonRecord="";

SearchResult result = (SearchResult)myenum.next();
Attributes attributes = result.getAttributes();

Attribute attr = attributes.get( "givenname" );
NamingEnumeration values = attr.getAll();

while( values.hasMore()) {
PersonRecord += values.next().toString();
PersonRecord += ", ";
}

attr = attributes.get( "sn" );
values = attr.getAll();

while( values.hasMore()) {
PersonRecord += values.next().toString();
PersonRecord += " - ";
}

attr = attributes.get( "mail" );
values = attr.getAll();

while( values.hasMore()) {
PersonRecord += values.next().toString();
}

System.out.println(PersonRecord);

}

ctx.close();

} catch(NamingException ne) { System.err.println(ne.toString()); }

}
}

Then a run through:


$ java getLdapDetails Doe
John, Doe - [email protected]



Reference

[tags]Java JNDI to LDAP, JNDI LDAP, LDAP Training School[/tags]



ldapsearch syntax

Problem

You want to perform an LDAP search



Solution

Starting this topic slowly, by giving practical tips on LDAP commands.

Predominately LDAP has a couple of main commands: ldapsearch and ldapmodify. With openLDAP there is additionally ldapadd, with netscape this is just ldapmodify -a.



Example



ldapsearch [ -v ] -x -D'user' -w'password'
[ -h host -p port ] -b base
-s depth 'criteria' [ attribs ]

User – ldap user, quite often directory manager, so usually you can get away with cn=Manager,your_tree.

Password – is LDAP password for user. If using the manager, password configured in the LDAP configs. If not user password it is set within LDAP itself.

Host and port – self-explanatory (default localhost on port 389).

Base – starting point within LDAP tree. Remember LDAP is hierarchal, so search will traverse down from this point.

Depth – can just be base (only show the the base level, do not transcend the tree) – specify sub to transcend.

Criteria – requirements for fields equaling a specific value, more on this shortly.

Attribs – fields to return, the dn is normally returned by default.

Demo:

ldapsearch -x -v -D'cn=Manager,dc=users,dc=net' -w secret -b'dc=users,dc=net' -s sub 'objectclass=*'

Basic LDAP syntax demo



Reference

[tags]ldapsearch syntax, ldapsearch demo, LDAP Training School[/tags]



Ldap reference – ldap result codes

Problem

Getting errors in LDAP



Solution

Click on LDAP error number below to see LDAP error description.



Example


0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,16,
17,18,19,20,21,32,
33,34,35,36,48,
49,50,51,52,53,54,64,
65,66,67,68,69,70,71,76

NumberMeaning
0Success
1Operations error
2Protocol error
3Timelimit exceeded
4Sizelimit exceeded
5Compare false
6Compare true
7Authentication method not supported
8Strong authentication required
9Parital results and referral received
10Referral received
11Administrative limit exceeded
12Unavailable critical extension
13Confidentiality required
14SASL bind in progress
16No such attribute
17Undefined attribute type
18Inappropriate matching
19Constraint violation
20Type or value exists
21Invalid syntax
32No such object
33Alias problem
34Invalid DN syntax
35Object is a leaf
36Alias deferenencing problem
48Inappropriate authentication
49Invalid credentials
50Insufficient access
51Server is busy
52Server is unavailable
53Server is unwilling to perform
54Loop detected
64Naming violation
65Object class violation
66Operation not permitted on non-leaf entry
67Operation not permitted on a RDN
68Entry already exists
69Cannot modify object class
70Results too large
71Affects multiple servers
76Virtual list view error


Reference