cn: epcpc5
host: epcpc5
description: research server
l: Narnia Data Center
cn: epcmsp
host: epcmsp
description: Service Processor
l: Narnia Data Center
cn: post62a
host: post62a
description: network printer
keyWords: netprinter
l: Narnia Data Center
cn: tst401
host: tst401
host: tst401.narnia.org
host: srv1ck41
description: Test Application Server
env: test
keyWords: linuxserver
keyWords: nonprod
keyWords: localperl
keyWords: sudoers
l: Data Center, Narnia
sysadm1: aslan
administratorContactInfo: sciops
nsHardwarePlatform: DellR730
####
#!/usr/bin/env perl
use strict;
use warnings;
# Bail out if no file is given as an argument.
my $ldap_file = shift || usage();
# To save output with extension .csv.
my $csv_file = "$ldap_file.csv";
# Preserve order of header labels.
my @header = qw(cn host description env keyWords l sysadm1 sysadm2 administratorContactInfo nsHardwarePlatform version);
# Boiler plate to open input and output files handles.
open my $in, '<', $ldap_file or die;
open my $out, '>', $csv_file or die;
# Write the header labels.
print $out join (',', @header[0..$#header]), "\n";
# Work engine.
{
# Record separator is a paragraph representation.
local $/="\n\n";
# Process one record at a time.
while(my $record = <$in>) {
my %data = ();
chomp $record; # Remove the record separator.
$data{@header} = (); # To label the data.
my @entries = split '\n', $record; # Create data entries.
# Work with each entry.
foreach my $entry (@entries){
if ($entry eq "") {
next;
}
my ($key, $value) = split ":", $entry, 2; # split only by first equal.
if ($key eq "" or $key eq "dn") {
next;
}
if ($value eq "") {
print "empty value: entry=$entry\n";
}
$value =~ s/^\s+//; # Clean leading spaces.
$value =~ s/\s+$//; # Clean trailing spaces.
if ( exists $data{$key} ) {
$data{$key} .= ("," . $value);
} else {
$data{$key} = $value;
}
}
# Separate entries with commas.
foreach my $key (keys %data) {
print "key=$key, value=$data($key)\n";
$data($key) =~ s/(^|$)/"/g if $data($key) =~ /,/;
}
my $row = join ',', (map{ $data{$_}?$data{$_}:""} @header);
# Write to output file.
print $out "$row\n";
}
}
# Dismiss file handles.
close $in;
close $out;
# Feed back to user.
print "$csv_file has been saved in the current directory\n";
sub usage {
print "Usage: $0 ldapfilename\n";
exit 1;
}
####
Global symbol "$data" requires explicit package name at ./ldap2csv.pl line 58.
Global symbol "$data" requires explicit package name at ./ldap2csv.pl line 59.
syntax error at ./ldap2csv.pl line 59, near "$data("
Global symbol "$data" requires explicit package name at ./ldap2csv.pl line 59.
Execution of ./ldap2csv.pl aborted due to compilation errors.
####
# Separate entries with commas.
foreach my $key (keys %data) {
print "key=$key, value=$data($key)\n";
$data($key) =~ s/(^|$)/"/g if $data($key) =~ /,/;
}