ldapsearch syntax part two

I purposely kept the first beginning ldap post simple, to help get across the syntax.

[problem]

Looking for a given user, searching my first name.

[/problem]

[solution]

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

[/solution]

[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

[/example]

[reference]

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

[/reference]

Solaris Network Tracing

[problem]

You are experiencing issues on the network, or a server process is playing up.

[/problem]

[solution]

You need to trace network connection. In the example I provide examples using Solaris and Linux. AIX is similar to Linux in the is regard – either using tcpdump or iptrace.

[/solution]

[example]

# network trace connection from hostname (solaris)

snoop -x0 src hostname

# network trace connections by port (linux)

tcpdump -A -v -v port 80

tcpdump: listening on eth0, link-type EN10MB (Ethernet), capture size 96 bytes
20:22:33.456278 IP (tos 0x0, ttl 128, id 63194, offset 0, flags [none], proto: TCP (6), length: 571) 10.0.0.8.4571 > bree.http: P 1:532(531) ack 1 win 32850
….GET /man/bash-1?sect=1&=kill HTTP/1.

[/example]

[reference]

[tags]Solaris Network Tracing, Solaris snoop, snoop, UNIX Coding School[/tags]

[/reference]

Perl TimeOut

[problem]

You have a script which runs too long and you want to time it out, after a given number
of seconds.

[/problem]

[solution]

Useful bit of code to time-out a section of your Perl script, via the alarm function.

See the example tab.

[/solution]

[example]


#!/usr/bin/perl

eval {

local %SIG;
$SIG{ALRM}=
sub{ die “timeout reached, after 20 seconds\n”; };
alarm 20;
print “sleeping for 60 secondsn”;
sleep 60; # This is where to put your code, between the alarms
alarm 0;
};

alarm 0;

if($@) { print “Error: $@\n”; }

exit(0);


__END__

[/example]

[reference]

[tags]Perl timeout, Perl Coding School[/tags]

[/reference]

Linux Debugging strace

[problem]

You have a problem with a process, running some job on a Linux box and need to see some debug information.

Sometimes the problem is a missing library, etc and you need to spot the missing dependency.

Symptoms could be a binary runs fine on one system and fails on another.

[/problem]

[solution]

On Linux use strace, which takes basically the same options as truss on Solaris.

[/solution]

[example]

You just use -e, like this:


strace -e’open’ ls
open(”/etc/ld.so.preload”, O_RDONLY) =
-1 ENOENT (No such file or directory)
open(”/etc/ld.so.cache”, O_RDONLY) = 3
open(”/lib/tls/librt.so.1″, O_RDONLY) = 3
open(”/lib/libtermcap.so.2″, O_RDONLY) = 3
open(”/lib/libacl.so.1″, O_RDONLY) = 3
open(”/lib/tls/libc.so.6″, O_RDONLY) = 3
open(”/lib/tls/libpthread.so.0″, O_RDONLY) = 3
open(”/lib/libattr.so.1″, O_RDONLY) = 3
open(”/usr/lib/locale/locale-archive”, O_RDONLY|O_LARGEFILE) = 3
open(”.”, O_RDONLY|O_NONBLOCK|O_LARGEFILE|O_DIRECTORY) = 3
open(”/etc/mtab”, O_RDONLY) = 3
open(”/proc/meminfo”, O_RDONLY) = 3

[/example]

[reference]

[tags]Linux strace, Linux, strace, UNIX Coding School[/tags]

[/reference]

Solaris Debugging

[problem]

You have a problem with a process, running some job on Solaris and need to see some debug information.

Sometimes the problem is a missing library, etc and you need to spot the missing dependency.

Symptoms could be a binary runs fine on one system and fails on another.

[/problem]

[solution]

Run truss with the binary, to spot all the files it opens and for additional information. Sometimes you can even spot where the log files are. 🙂

[/solution]

[example]

This will show system process debug (solaris) for all exec/reads for a running process.

truss -xall -vall -rall -t'read' -p PID

This will run truss with the process.

truss -xall -vall -rall -t'read' program

[/example]

[reference]

[tags]Solaris Debugging, truss, UNIX Coding School[/tags]

[/reference]

Java JNDI talk to LDAP

[problem]

You want to talk to LDAP from Java.

[/problem]

[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.

[/solution]

[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]

[/example]

[reference]

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

[/reference]

ldapsearch syntax

[problem]

You want to perform an LDAP search

[/problem]

[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.

[/solution]

[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

[/example]

[reference]

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

[/reference]

Perl WIN32 OLE – Outlook save text

[problem]

How to use Perl to connect to MS Outlook. Then descend through given folders and save items to disk, as text files.

[/problem]

[solution]

I wrote this some time ago, to traverse predefined outlook mail folders, saving items with given subject to text.

Requires WIN32:OLE perl module (which comes with activeperl by default).

Hardcoded is the upload and uploaded mail folders. Also a subject that contains – pattern: upload.

I used one outlook rule to move items from a specific source, with this subject into upload.

[/solution]

[example]

Here is the code – if you have any dramas with it, leave a comment.


#!perl

use Win32::OLE qw(in with);
use Win32::OLE::Const 'Microsoft Outlook';

# Connect to a running version of Outlook
eval { $Outlook =
   Win32::OLE->GetActiveObject('Outlook.Application')
};

die "Outlook not installed" if $@;

# If that fails start up Outlook
unless(defined $Outlook) {
   $Outlook =
     Win32::OLE->new('Outlook.Application', 'Quit')
   or die "Opps, cannot start Outlook";
}

# This appears to return a ref to the object
$namespace = $Outlook->GetNamespace('MAPI');
$thisFolder=$namespace->Folders("Mailbox - mailboxna")->
   Folders('upload');
$toFolder=$namespace->Folders("Mailbox - mailboxna")->
   Folders('uploaded');

# Workaround to be able to extract key/value pairs
%thisHash=%{$thisFolder};
$name=$thisHash{'Name'};

# This is the number of items in designated folder
$count=$thisHash{'Items'}{'Count'};
open(LOGFH,">> ol_save_to_text.log")
   or die("cannot open log filen");

# Drop out if there are no mail items in this folder
if($count > 0) {

   print LOGFH "Count: $count for $namen";

   $filename='yourname';
   open(FH,"> $filename")
   or die ("cannot open $filenamen");

   for($i=1;$i<=$count;$i++) {
     print LOGFH "Count: $countn";

     $oItems=$thisFolder->Items(1);

     %thisItem=%{$oItems};
     $subject=$thisItem{'Subject'};

     if($subject =~ /pattern: upload/) {
       print LOGFH "$i: $subjectn";
       $body=$thisItem{'Body'};
       print FH "$body";
       $oItems->Move($toFolder);
     } else {
       $nonitem+=1;
     }

     $oItems->Move($toFolder);
   }

} else { print LOGFH "No Files to Processn"; }

close(LOGFH);
1;

[/example]

[reference]

Microsoft Outlook Keyboard Shortcuts – Courtesy of RNIB

[tags]MS Outlook OLE Perl, MS Outlook, OLE, Perl win32, cygwin, Perl, Perl Coding School[/tags]

[/reference]

Perl libcurl demo

[problem]

You want to use libcurl, driven through Perl.

[/problem]

[solution]

Beautiful for parse HTML and either extracted (screen scraping) content or performing actions based on results.

See the examples tab for this simple script, demonstrating the libcurl API for Perl.

[/solution]

[example]


#!/usr/bin/perl

$url="http://perl.coding-school.com/"; # set your url here
$|++;

use Curl::easy;
# Init the curl session

my $curl= Curl::easy::init() or die "curl init failed!n err: $!n";

sub body_callback {
   my ($chunk,$context)=@_;
   push @{$context}, $chunk;
   return length($chunk);
}

Curl::easy::setopt
   ($curl, CURLOPT_PROXY, $proxy) if($proxy);
Curl::easy::setopt
   ($curl, CURLOPT_PROXYPORT, $proxyport) if($proxyport);
Curl::easy::setopt
   ($curl, CURLOPT_SSL_VERIFYHOST, 0);
Curl::easy::setopt
   ($curl, CURLOPT_SSL_VERIFYPEER, 0);
Curl::easy::setopt
   ($curl, CURLOPT_URL, $url);
Curl::easy::setopt
   ($curl, CURLOPT_WRITEFUNCTION, &body_callback);

my @body;

Curl::easy::setopt
   ($curl, CURLOPT_FILE, @body);
Curl::easy::setopt
   ($curl, CURLOPT_ERRORBUFFER, "errbuf");
if (Curl::easy::perform
   ($curl) != 0) { print "Failed : $errbufn"; };
Curl::easy::cleanup($curl);

# Separate each line into one element in array
@lines=();

foreach (@body) { push(@lines,split('n', $_, 9999)); }

foreach (@lines) {
   # just to demonstrate it works!
   if(/icons/) { print("$_n"); }
}

exit(0);

Here is a demo screen shot of this code using perl and libcurl.

[/example]

[reference]

[tags]Perl libcurl demo, Perl libcurl, Perl, libcurl, curl, Perl Coding School[/tags]

[/reference]

Perl SHA digest

[problem]

You want to generate a SHA digest for a given string.

[/problem]

[solution]

Perl has great encryption and digesting algorithms.

In the example tab we use the Digest Perl module.

[/solution]

[example]


perl -M'Digest::SHA1 qw(sha1_hex)'
-e '$dig=sha1_hex("my big test"); print "$dign";'

419e6139a21f51a3f2ea1a783cfe536a0dada873

[/example]

[reference]

[tags]Perl SHA Digest, Perl, SHA, Encryption, Perl Coding School[/tags]

[/reference]