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]



Solaris Network Tracing

Problem

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



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.



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.



Reference

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



Perl TimeOut

Problem

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



Solution

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

See the example tab.



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__

View screen shot demo of perl timeout

view screen shot of perl timeout demo



Reference

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



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.



Solution

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



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



Reference

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



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.



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



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



Reference

[tags]Solaris Debugging, truss, UNIX Coding 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 - john.doe@demo.net



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]



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.



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.



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;



Reference

Microsoft Outlook Keyboard Shortcuts – Courtesy of RNIB

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



Perl libcurl demo

Problem

You want to use libcurl, driven through Perl.



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.



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.



Reference

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