Created
January 23, 2018 17:15
-
-
Save domq/0ab7de2f2a2a295883b591632a5ca7c8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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