Skip to content

Instantly share code, notes, and snippets.

@domq
Created January 23, 2018 17:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save domq/0ab7de2f2a2a295883b591632a5ca7c8 to your computer and use it in GitHub Desktop.
Save domq/0ab7de2f2a2a295883b591632a5ca7c8 to your computer and use it in GitHub Desktop.
#!/usr/bin/perl -w
use strict;
use utf8;
use Encode qw(decode);
use Text::CSV;
use Net::LDAP;
use Error qw(:try);
my $ldap = Net::LDAP->new( 'ldap.epfl.ch' ) or die "$@";
my $mesg = $ldap->bind ; # an anonymous bind
$mesg = $ldap->search( # perform a search
base => "o=epfl,c=ch",
filter => "(&(objectclass=person)(ou=STI-IT))",
sizelimit => 50
);
$mesg->code && die $mesg->error;
my $outfile = "ldap-epfl.csv";
my $fh;
open $fh, ">:utf8", $outfile or die "$outfile: $!";
my $csv = Text::CSV->new ({binary => 1});
$csv->eol ("\n");
sub _decode {
my ($bin) = @_;
my $txt;
return decode('UTF-8', $bin, Encode::FB_CROAK);
}
sub Net::LDAP::Entry::get_utf8 {
my $self = shift;
return wantarray ?
map { _decode($_) }
($self->get_value(@_)) :
_decode(scalar($self->get_value(@_)));
}
sub first_shortest {
my @names = @_;
my %size_histogram;
foreach my $gn (@names) {
$size_histogram{length($gn)}++;
}
my ($shortest_length) = sort {$a <=> $b} keys %size_histogram;
my ($shortest) = grep { length($_) == $shortest_length } @names;
return $shortest;
}
our %getters = (
givenname => sub { first_shortest(shift->get_utf8("givenname")) },
sn => sub { first_shortest(shift->get_utf8("sn")) },
orgs23 => sub {
my ($entry) = @_;
my $dn = $entry->dn();
my ($ou2, $ou3) = $dn =~ m/ou=([^,]+),ou=([^,]+),o=epfl/;
return (uc($ou2), uc($ou3));
},
);
foreach my $entry ($mesg->entries) {
$csv->print($fh, [map {
$getters{$_} ?
$getters{$_}->($entry) :
scalar($entry->get_utf8($_));
} qw( ou orgs23 title title;lang-en givenname sn personalTitle userClass mail organizationalStatus)]);
}
close($fh) or die "$outfile: $!";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment