-
Notifications
You must be signed in to change notification settings - Fork 20
/
file2ldif.pl
383 lines (323 loc) · 10.4 KB
/
file2ldif.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
#!/usr/bin/perl -w
#====================================================================
# Script to convert CSV or LDIF into LDIF
#
# Copyright (C) 2009 Clement OUDOT
# Copyright (C) 2009 LTB-project.org
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# GPL License: http://www.gnu.org/licenses/gpl.txt
#
#====================================================================
#====================================================================
# Configuration
#====================================================================
# Containers begin and end characters for replacement
my $beginc = "{";
my $endc = "}";
# Write changes and not full entries
my $change = 1;
# CSV delimiter (default is ",")
my $csv_delimiter = ";";
# CSV multi values delimiter
my $csv_multivalues_delimiter = ",";
# Strip CSV headers (jump to second line)
my $csv_strip_headers = 1;
# Mapping configuration
my $map = {
l_person => {
dn => 'uid={(lc)uid},ou=users,dc=example,dc=com',
objectClass =>
[ 'top', 'person', 'organizationalPerson', 'inetOrgPerson' ],
cn => '{cn}',
sn => '{(uc)sn}',
givenName => '{(ucfirstlc)givenname}',
mail => '{(fmail)givenname}.{(fmail)sn}@example.com',
userPassword => '{(random12)}',
},
l_group => {
dn => 'cn={employeetype},ou=groups,dc=example,dc=com',
objectClass => [ 'top', 'groupOfUniqueNames' ],
uniqueMember => 'cn=empty',
},
l_group_add => {
change_op => 'add',
dn => 'cn={(lc)employeetype},ou=groups,dc=example,dc=com',
uniqueMember => 'uid={(lc)uid},ou=users,dc=example,dc=com',
},
l_group_del => {
change_op => 'delete',
dn => 'cn={(lc)employeetype},ou=groups,dc=example,dc=com',
uniqueMember => 'cn=empty',
},
c_person => {
dn => 'uid={1},ou=users,dc=example,dc=com',
objectClass =>
[ 'top', 'person', 'organizationalPerson', 'inetOrgPerson' ],
uid => '{1}',
givenName => '{2}',
sn => '{3}',
cn => '{2} {3}',
},
c_group => {
dn => 'cn={1},ou=groups,dc=example,dc=com',
objectClass => [ 'top', 'groupOfUniqueNames' ],
cn => '{1}',
uniqueMember => 'uid={2},ou=users,dc=example,dc=com',
},
};
#====================================================================
# Modules
#====================================================================
use Net::LDAP::LDIF;
use strict;
#====================================================================
# Get command line arguments
#====================================================================
# TODO: use getopts
# Task
my $task = shift @ARGV;
# Input file
my $file = shift @ARGV;
# Changetype (add, modify, delete, modrdn)
my $changetype = shift @ARGV;
$changetype = "add" unless $changetype;
# Output file
my $outldif = Net::LDAP::LDIF->new( "$task.ldif", "w", change => $change );
my $inldif;
# Determine input type file (CSV or LDIF)
my ($type) = ( $file =~ m/.*\.(\w+)/ );
# If CSV, generate a tmp LDIF file
if ( $type =~ m/csv/i ) {
# Load Text::CSV module
use Text::CSV;
# Open CSV
my $csv = Text::CSV->new(
{
sep_char => $csv_delimiter,
binary => 1,
}
);
open( CSV, "<", $file ) or die $!;
# Parse CSV
$inldif = Net::LDAP::LDIF->new( "$file.ldif", "w" );
while (<CSV>) {
# Strip headers
next if ( ( $. == 1 ) and ( $csv_strip_headers == 1 ) );
# Parse CSV line
if ( $csv->parse($_) ) {
my @columns = $csv->fields();
# Write every column as attribute
my $entry = Net::LDAP::Entry->new('o=fakedn');
for my $i ( 0 .. $#columns ) {
if ($csv_multivalues_delimiter) {
my @values =
split( /\Q$csv_multivalues_delimiter\E/, $columns[$i] );
$entry->add( $i + 1 => \@values );
}
else {
$entry->add( $i + 1 => $columns[$i] );
}
}
$inldif->write_entry($entry);
}
else {
# Error in parsing
my $err = $csv->error_input;
print STDERR "Failed to parse line: $err\n";
}
# Next line
next;
}
close CSV;
$inldif->done();
$inldif = Net::LDAP::LDIF->new("$file.ldif");
}
else {
$inldif = Net::LDAP::LDIF->new($file);
}
# Parse LDIF
while ( not $inldif->eof() ) {
my $entry = $inldif->read_entry();
next unless $entry;
if ( $inldif->error() ) {
print STDERR "Error msg: ", $inldif->error(), "\n";
print STDERR "Error lines:\n", $inldif->error_lines(), "\n";
}
else {
# Replace strings in map
my %localmap = %{ $map->{$task} };
while ( my ( $k, $v ) = each %localmap ) {
if ( ref($v) eq "ARRAY" ) {
my @values = @$v;
my @all_values;
foreach (@values) {
my $new_values = &generate_value( $entry, $_ );
push @all_values, @$new_values if $new_values;
}
$v = \@all_values;
}
else {
$v = &generate_value( $entry, $v );
}
$localmap{$k} = $v;
}
# DN
my $dn = shift @{ $localmap{'dn'} };
delete $localmap{dn};
# Change operation
my $change_op = shift @{ $localmap{change_op} };
delete $localmap{change_op};
$change_op = "add" unless $change_op;
# Remove empty values
while ( my ( $key, $value ) = each(%localmap) ) {
delete $localmap{$key} if ( $value eq "" );
delete $localmap{$key}
if ( ref($value) eq "ARRAY" and @$value == 0 );
}
# Write entry
my $outentry = Net::LDAP::Entry->new($dn);
$outentry->changetype($changetype);
$outentry->$change_op(%localmap);
$outldif->write_entry($outentry);
if ( my $ldif_error = $outldif->error() ) {
print STDERR "Fail to add entry in LDIF: $ldif_error\n";
}
}
}
# Takes all values of wanted attribute
# Removes the whitespaces from begin and end
# Apply subroutine if any
# @return ARRAYREF of values
sub replace_value {
my $entry = shift;
my $key = shift;
my $sub;
my $attr;
my $value;
my @result;
# Check subroutine presence
if ( $key =~ m/\((.*)\)(.*)?/ ) {
$sub = $1;
$attr = $2;
# If no attribute, apply only subroutine and return value
unless ($attr) {
return [ &apply_sub( undef, $sub ) ];
}
}
else { $attr = $key }
# Replace DN
if ( $attr eq "dn" ) { $value = [ $entry->dn() ]; }
# Get all attribute values
else { $value = $entry->get_value( $attr, asref => 1 ); }
# Empty value
return "" unless defined $value;
foreach my $val (@$value) {
my $safe_val = $val;
# Trim begin and end whitespaces
$safe_val =~ s/^\s+|\s+$//g;
# Apply subroutine if any
$safe_val = &apply_sub( $val, $sub ) if ($sub);
push @result, $safe_val;
}
return \@result;
}
# Create the new values
# Call replace_value to get the mapping
# @return ARRAYREF of new values
sub generate_value {
my $entry = shift;
my $value = shift;
my $key;
my @result;
if ( $value =~ m/$beginc([^$endc]*)?$endc/ ) {
my @keys = ( $value =~ m/$beginc([^$endc]*)?$endc/g );
# If multiple keys, use only first attribute value
if ( $#keys > 0 ) {
my $hValues = {};
foreach $key (@keys) {
my $new_values = &replace_value( $entry, $key );
if ($new_values) {
$hValues->{$key} = shift @$new_values;
}
}
my $safe_value = $value;
$safe_value =~ s/$beginc([^$endc]*)?$endc/$hValues->{$1}/ge;
push @result, $safe_value;
}
else {
# Else use all attributes values
$key = shift @keys;
my $new_values = &replace_value( $entry, $key );
if ($new_values) {
foreach my $new_value (@$new_values) {
my $safe_value = $value;
$safe_value =~ s/$beginc([^$endc]*)?$endc/$new_value/ge;
push @result, $safe_value;
}
}
}
}
else {
push @result, $value;
}
return \@result;
}
# Apply subroutine
sub apply_sub {
my $value = shift;
my $sub = shift;
$value = lc($value) if ( $sub eq "lc" );
$value = lcfirst($value) if ( $sub eq "lcfirst" );
$value = uc($value) if ( $sub eq "uc" );
$value = ucfirst($value) if ( $sub eq "ucfirst" );
$value = ucfirst( lc($value) ) if ( $sub eq "ucfirstlc" );
$value = &fmail($value) if ( $sub eq "fmail" );
if ( $sub =~ /^random(\d+)/ ) {
$value = &randomval($1);
}
return $value;
}
# Formate values for mail address
sub fmail {
my $value = shift;
# Force lower case
$value = lc($value);
# Replace spaces by -
$value =~ s/(\s+)/-/g;
# Remove accents
eval { require Text::Unaccent };
if ($@) { return $value; }
else {
$value = unac_string( 'UTF-8', $value );
return $value;
}
}
# Generate random value
sub randomval {
my $length = shift;
my $value;
eval { require String::Random };
if ($@) { return $value; }
else {
my $pass = String::Random->new;
$value = $pass->randregex("[A-Za-z0-9]{$length}");
}
return $value;
}
#====================================================================
# Exit
#====================================================================
$inldif->done();
$outldif->done();
unlink "$file.ldif" if ( $type =~ m/csv/i );
exit 0;