-
Notifications
You must be signed in to change notification settings - Fork 0
/
ldif-gen.py
executable file
·3086 lines (2706 loc) · 118 KB
/
ldif-gen.py
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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python3
#
# LDIF file generator
#
# Written by: Mark Reynolds ([email protected])
#
# Created: 5/20/2014
# Updated: 2/12/2024
#
import sys
import signal
import optparse
import random
from optparse import IndentedHelpFormatter
import textwrap
VERSION = '1.0'
verbose = False
DataDir = "@templatedir@"
padding = True
random_all = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqurstuvwxyz0123456789_#@%&()?~$^`~*-=+{}|"\'.,<>'
random_alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqurstuvwxyz'
random_alphanum = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqurstuvwxyz0123456789'
#default user attributes
user_attrs = ['description', 'departmentnumber', 'employeeyype', 'homephone', 'initials',
'telephonenumber', 'facsimiletelephonenumber', 'mobile', 'pager', 'manager',
'secretary', 'roomnumber', 'carlicense', 'l', 'mail', 'postaladdress'
'title', 'usercertificate;binary']
# internal list of first and last names in case no "name" files are available
firstnames = ('Adam', 'Alice', 'Brad', 'Brenda', 'Christopher', 'Christine', 'David', 'Diana',
'Mark', 'Rob', 'Fred', 'Felicia', 'Ludwig', 'George', 'Gloria', 'Hank', 'Heather',
'Simon', 'Julie', 'Thierry', 'Willie')
lastnames = ('Smith', 'Johnson', 'Bordaz', 'Krispenz', 'Pichugin', 'Reynolds', 'Mosconi',
'Carter', 'Brown', 'Jenson', 'Mullen', 'Garcia', 'Montbleau', 'Rose', 'Woods',
'Salinas', 'Sholl', 'Crittenden', 'Dugan', 'Griffith', 'Reynolds', 'Richards', 'Key')
# Misc lists
area_codes = ("303", "415", "408", "510", "804", "818", "213", "206", "714", "610", "650", "512")
seqSet = {}
#
# Org Chart Entries
#
#
# CEO
ceo = {"uid": "ceo", "givenname": "John", "sn": "Budd", "cn": "John Budd", "title": "CEO"}
# Executive Presidents
ep0 = {"uid": "exec_president0", "givenname": "Paul", "sn": "Grant", "cn": "Paul Grant", "title": "Executive President"}
ep1 = {"uid": "exec_president1", "givenname": "Jill", "sn": "Peterson", "cn": "Jill Peterson",
"title": "Exective President"}
exec_presidents = (ep0, ep1)
# Presidents
p0 = {"uid": "president0", "givenname": "Pete", "sn": "Dunne", "cn": "Pete Dunne", "title": "President"}
p1 = {"uid": "president1", "givenname": "Jannet", "sn": "Keys", "cn": "Jannet Keys", "title": "President"}
p2 = {"uid": "president2", "givenname": "Anne", "sn": "Meissner", "cn": "Anne Meissner", "title": "President"}
presidents = (p0, p1, p2)
# Vice Presidents
vp0 = {"uid": "vice_president0", "givenname": "Jack", "sn": "Cho", "cn": "Jack Cho", "title": "Vice President"}
vp1 = {"uid": "vice_president1", "givenname": "Diane", "sn": "Smith", "cn": "Diane Smith", "title": "Vice President"}
vp2 = {"uid": "vice_president2", "givenname": "Alex", "sn": "Merrells", "cn": "Alex Merrells",
"title": "Vice President"}
vp3 = {"uid": "vice_president3", "givenname": "Yumi", "sn": "Mehta", "cn": "Yumi Mehta", "title": "Vice President"}
vp4 = {"uid": "vice_president4", "givenname": "Michael", "sn": "Natkovich", "cn": "Michael Natkovich",
"title": "Vice President"}
vp5 = {"uid": "vice_president5", "givenname": "Keith", "sn": "Lucus", "cn": "Keith Lucus", "title": "Vice President"}
vice_presidents = (vp0, vp1, vp2, vp3, vp4, vp5)
# Directors
d0 = {"uid": "director0", "givenname": "Chris", "sn": "Harrison", "title": "Director", "cn": "Chris Harrison"}
d1 = {"uid": "director1", "givenname": "Jane", "sn": "Baker", "title": "Director", "cn": "Jane Baker"}
d2 = {"uid": "director2", "givenname": "Ed", "sn": "Becket", "title": "Director", "cn": "Ed Becket"}
d3 = {"uid": "director3", "givenname": "Will", "sn": "Stevenson", "title": "Director", "cn": "Will Stevenson"}
d4 = {"uid": "director4", "givenname": "Kieran", "sn": "Beckham", "title": "Director", "cn": "Kieran Beckham"}
d5 = {"uid": "director5", "givenname": "Greg", "sn": "Emerson", "title": "Director", "cn": "Greg Emerson"}
d6 = {"uid": "director6", "givenname": "Ian", "sn": "Parker", "title": "Director", "cn": "Ian Parker"}
d7 = {"uid": "director7", "givenname": "Liem", "sn": "Olson", "title": "Director", "cn": "Liem Olson"}
d8 = {"uid": "director8", "givenname": "George", "sn": "Cruise", "title": "Director", "cn": "George Cruise"}
d9 = {"uid": "director9", "givenname": "Yoshiko", "sn": "Tucker", "title": "Director", "cn": "Yoshiko Tucker"}
directors = (d0, d1, d2, d3, d4, d5, d6, d7, d8, d9)
# Managers
m0 = {'uid': 'manager0', 'givenname': 'Teresa', 'sn': 'Chan', 'cn': 'Teresa Chan', 'title': 'manager'}
m1 = {'uid': 'manager1', 'givenname': 'Tom', 'sn': 'Anderson', 'cn': 'Tom Anderson', 'title': 'manager'}
m2 = {'uid': 'manager2', 'givenname': 'Olga', 'sn': 'Young', 'cn': 'Olga Young', 'title': 'manager'}
m3 = {'uid': 'manager3', 'givenname': 'Bill', 'sn': 'Graham', 'cn': 'Bill Graham', 'title': 'manager'}
m4 = {'uid': 'manager4', 'givenname': 'Todd', 'sn': 'Hoover', 'cn': 'Tom Hoover', 'title': 'manager'}
m5 = {'uid': 'manager5', 'givenname': 'Ken', 'sn': 'Hamilton', 'cn': 'Ken Hamilton', 'title': 'manager'}
m6 = {'uid': 'manager6', 'givenname': 'Christine', 'sn': 'Jobs', 'cn': 'Christine Jobs', 'title': 'manager'}
m7 = {'uid': 'manager7', 'givenname': 'Joanna', 'sn': 'Lake', 'cn': 'Joanna Lake', 'title': 'manager'}
m8 = {'uid': 'manager8', 'givenname': 'Kim', 'sn': 'Remley', 'cn': 'Kim Remley', 'title': 'manager'}
m9 = {'uid': 'manager9', 'givenname': 'Nick', 'sn': 'Pennebaker', 'cn': 'Nick Pennebaker', 'title': 'manager'}
m10 = {'uid': 'manager10', 'givenname': 'Ted', 'sn': 'Hardy', 'cn': 'Ted Hardy', 'title': 'manager'}
m11 = {'uid': 'manager11', 'givenname': 'Tanya', 'sn': 'Nielsen', 'cn': 'Tanya Nielsen', 'title': 'manager'}
m12 = {'uid': 'manager12', 'givenname': 'Sam', 'sn': 'Madams', 'cn': 'Sam Madams', 'title': 'manager'}
m13 = {'uid': 'manager13', 'givenname': 'Judy', 'sn': 'Stewart', 'cn': 'Judy Stewart', 'title': 'manager'}
m14 = {'uid': 'manager14', 'givenname': 'Martha', 'sn': 'Kidman', 'cn': 'Martha Kidman', 'title': 'manager'}
m15 = {'uid': 'manager15', 'givenname': 'Leo', 'sn': 'Knuth', 'cn': 'Leo Knuth', 'title': 'manager'}
m16 = {'uid': 'manager16', 'givenname': 'Cecil', 'sn': 'Guibas', 'cn': 'Cecil Guibas', 'title': 'manager'}
m17 = {'uid': 'manager17', 'givenname': 'Jay', 'sn': 'Hows', 'cn': 'Jay Hows', 'title': 'manager'}
orgManagers = (m0, m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11, m12, m13, m14, m15, m16, m17)
# localities
localities = ("Mountain View", "Redmond", "Redwood Shores", "Armonk", "Cambridge", "Santa Clara",
"Sunnyvale", "Alameda", "Philadelphia", "Reading", "Cupertino", "Menlo Park", "Palo Alto",
"Orem", "San Jose", "San Francisco", "Milpitas", "Hartford", "Windsor", "Boston",
"Westford", "New York", "Detroit", "Austin", "Dallas", "Denver")
# Titles
titles = ("Senior", "Master", "Associate", "Junior", "Chief", "Supreme", "Elite", "Greenhorn")
# Org Units
orgUnits = ('CEO', 'Executive Presidents', 'Presidents', 'Vice Presidents', 'Directors', 'Managers')
def write_org_units(LDIF, suffix):
for unit in orgUnits:
LDIF.write('dn: ou=' + unit + ',' + suffix + '\n')
LDIF.write('objectclass: top\n')
LDIF.write('objectclass: organizationalUnit\n')
LDIF.write('ou: ' + unit + '\n')
LDIF.write('\n')
def write_org_entry(LDIF, suffix, entry):
LDIF.write('dn: uid=%s,%s\n' % (entry['uid'], suffix))
LDIF.write('objectclass: top\n')
LDIF.write('objectclass: person\n')
LDIF.write('objectclass: inetorgperson\n')
LDIF.write('objectclass: organizationalPerson\n')
LDIF.write('uid: ' + entry['uid'] + '\n')
LDIF.write('cn: ' + entry['cn'] + '\n')
LDIF.write('sn: ' + entry['sn'] + '\n')
LDIF.write('givenname: ' + entry['givenname'] + '\n')
LDIF.write('employeenumber: ' + get_random_value("int", 6) + '\n')
LDIF.write('homephone: ' + get_random_value("tele") + '\n')
LDIF.write('initials: ' + str(entry['uid'])[:2] + '\n')
LDIF.write('telephonenumber: ' + get_random_value("tele") + '\n')
LDIF.write('facsimiletelephonenumber: ' + get_random_value("tele") + '\n')
LDIF.write('mobile: ' + get_random_value("tele") + '\n')
LDIF.write('pager: ' + get_random_value("tele") + '\n')
LDIF.write('manager: ' + get_manager(entry) + '\n')
LDIF.write('secretary: ' + get_random_value("secretary") + '\n')
LDIF.write('roomnumber: ' + get_random_value("int", 5) + '\n')
LDIF.write('carlicense: ' + get_random_value("alpha", 7) + '\n')
LDIF.write('l: ' + random_pick(localities) + '\n')
LDIF.write('mail: ' + get_email_address(entry) + '\n')
LDIF.write('postaladdress: ' + entry['suffix'] + ' Dept #' + str(random.randomint(1, 25)) + ', Room#' +
str(random.randomint(1, 1000)) + '\n')
LDIF.write("usercertificate;binary:: MIIBvjCCASegAwIBAgIBAjANBgkqhkiG9w0BA" +
"QQFADAnMQ8wDQYD\n VQQDEwZjb25maWcxFDASBgNVBAMTC01NUiBDQSBDZXJ0" +
"MB4XDTAxMDQwNTE1NTEwNloXDTExMDcw\n NTE1NTEwNlowIzELMAkGA1UEChM" +
"CZnIxFDASBgNVBAMTC01NUiBTMSBDZXJ0MIGfMA0GCSqGSIb3\n DQEBAQUAA4" +
"GNADCBiQKBgQDNlmsKEaPD+o3mAUwmW4E40MPs7aiui1YhorST3KzVngMqe5Pb" +
"ObUH\n MeJN7CLbq9SjXvdB3y2AoVl/s5UkgGz8krmJ8ELfUCU95AQls321RwB" +
"dLRjioiQ3MGJiFjxwYRIV\n j1CUTuX1y8dC7BWvZ1/EB0yv0QDtp2oVMUeoK9" +
"/9sQIDAQABMA0GCSqGSIb3DQEBBAUAA4GBADev\n hxY6QyDMK3Mnr7vLGe/HW" +
"EZCObF+qEo2zWScGH0Q+dAmhkCCkNeHJoqGN4NWjTdnBcGaAr5Y85k1\n o/vO" +
"AMBsZePbYx4SrywL0b/OkOmQX+mQwieC2IQzvaBRyaNMh309vrF4w5kExReKfj" +
"R/gXpHiWQz\n GSxC5LeQG4k3IP34\n")
LDIF.write('\n')
def write_org_chart(LDIF, suffix):
# Write the organizational units for each org level
write_org_units(LDIF, suffix)
# set 'suffix' and 'dnval'
ceo['suffix'] = suffix
ceo['dnval'] = ceo['uid']
write_org_entry(LDIF, 'ou=CEO,' + suffix, ceo)
for ep in exec_presidents:
ep['suffix'] = suffix
ep['dnval'] = ep['uid']
write_org_entry(LDIF, 'ou=Executive Presidents,' + suffix, ep)
for p in presidents:
p['suffix'] = suffix
p['dnval'] = p['uid']
write_org_entry(LDIF, 'ou=Presidents,' + suffix, p)
for vp in vice_presidents:
vp['suffix'] = suffix
vp['dnval'] = vp['uid']
write_org_entry(LDIF, 'ou=Vice Presidents,' + suffix, vp)
for d in directors:
d['suffix'] = suffix
d['dnval'] = d['uid']
write_org_entry(LDIF, 'ou=Directors,' + suffix, d)
for m in orgManagers:
m['suffix'] = suffix
m['dnval'] = m['uid']
write_org_entry(LDIF, 'ou=Managers,' + suffix, m)
#
# get_manager
#
def get_manager(user):
if user['createorgchart']:
org_idx = random.randint(0, len(orgManagers) - 1)
dn = ('uid=' + orgManagers[org_idx]['uid'] + ',ou=Managers,' +
user['suffix'])
return dn
else:
first = firstnames[random.randint(0, len(firstnames) - 1)]
last = lastnames[random.randint(0, len(lastnames) - 1)]
return 'uid=' + first[0:1] + last[:] + ',' + user['suffix']
#
# Return an email address based off the user info
#
def get_email_address(user):
dncomps = user['suffix'].split(',')
domain = ''
first = 1
for val in dncomps:
val = val.replace(' ', '')
parts = val.split('=')
val = parts[1]
if first:
domain = domain + val
first = 0
else:
domain = domain + '.'
domain = domain + val
return user['dnval'].replace(' ', '.') + '@' + domain
#
# Return a random value of the specified type:
#
# all, alpha, alphanum, int, tele, ssn, secretary
#
def get_random_value(val_type, length=0):
if length:
random_len = length
else:
random_len = random.randint(10, 30)
if val_type == 'int':
if length == 0:
# get a number that can be long enough to hold a credit number
length = '9' * 16
else:
length = '9' * length
return str(random.randint(1, int(length)))
if val_type == 'alpha':
return (''.join((random.choice(random_alpha)
for i in range(1, random_len))))
if val_type == 'alphanum' or val_type == 'all':
return (''.join((random.choice(random_alphanum)
for i in range(random_len))))
if val_type == 'tele':
areacode = area_codes[random.randint(0, len(area_codes) - 1)]
prefix = str(random.randint(100, 999))
postfix = str(random.randint(1000, 9999))
return "+1 " + areacode + " " + prefix + "-" + postfix
if val_type == 'ssn':
one = str(random.randint(0, 900) + 99)
two = str(random.randint(0, 90) + 9)
three = str(random.randint(0, 9000) + 999)
return one + '-' + two + '-' + three
if val_type == 'secretary':
return ('cn=' + firstnames[random.randint(0, len(firstnames) - 1)] +
' ' + lastnames[random.randint(0, len(lastnames) - 1)])
return ''.join((random.choice(random_all) for i in xrange(random_len)))
#
# Return a randomly selection value from the provided list of values
#
def random_pick(values):
val_count = len(values)
val_count -= 1
idx = random.randint(0, val_count)
return values[idx].lstrip()
#
# Maintain a hash (index position) for each attribute we are using seq sets for
#
def seq_pick(attr, values):
global seqSet
if attr in seqSet:
idx = seqSet[attr]
else:
seqSet[attr] = 0
idx = 0
seqSet[attr] += 1
if seqSet[attr] >= len(values):
# reset to the front
seqSet[attr] = 0
return values[idx].lstrip()
#
# Open the output LDIF file
#
def open_ldif(file_name):
file_opened = 0
LDIF = None
if file_name:
if verbose:
print ('Opening LDIF file: ' + file_name)
try:
LDIF = open(file_name, "w")
except IOError:
print ("Can't open file: " + file_name)
exit(1)
else:
while file_opened == 0:
file_name = input(' Enter output LDIF name [/tmp/out.ldif]: ')
if file_name == '':
file_name = '/tmp/out.ldif'
try:
LDIF = open(file_name, "w")
file_opened = 1
except IOError:
print ("Can\'t open file: " + file_name)
file_name = ''
print ('Building LDIF file (%s)...' % file_name)
return LDIF
#
# Return a number string index
# zero "padding" allow the entry to work with ldclt
#
def get_index(idx, num_users):
if padding:
zero_len = len(str(num_users)) - len(str(idx))
index = '0' * zero_len
index = index + str(idx)
return index
else:
return idx
#
# Process a list of attribute value pairs. Check for special keywords, and
# return the dn
#
def process_attr_list(LDIF, value_list, index, mod_list=False):
dn = ''
for value_pair in value_list:
value_pair = value_pair.rstrip()
if value_pair == '':
break
attr_values = value_pair.split(':')
if len(attr_values) > 1:
attr = attr_values[0].lower()
attr_value = attr_values[1].lstrip()
# attr: RANDOM:int:9
if attr_value == 'RANDOM':
# We have a random value, see if the 'type' and 'length' was
# provided.
# type: all(default), alpha, int
# description: RANDOM
# description: RANDOM:alpha
# description: RANDOM:alpha:10
if len(attr_values) == 2:
value_pair = attr + ": " + get_random_value("all")
elif len(attr_values) == 3:
value_pair = (attr + ": " +
get_random_value(attr_values[2].lstrip()))
elif len(attr_values) >= 4:
value_pair = (attr + ": " +
get_random_value(attr_values[2].lstrip(),
int(attr_values[3].lstrip())))
elif attr_value == 'random_pick':
# Okay we have random values have to gather and select
if len(attr_values) > 2:
values = attr_values[2].split(';')
value_pair = attr + ": " + random_pick(values)
elif attr_value == 'SEQ_SET':
# Okay we have sequential set values to deal with
if len(attr_values) > 2:
values = attr_values[2].split(';')
value_pair = attr + ": " + seq_pick(attr, values)
if attr in user_attrs:
user_attrs.remove(attr)
else:
print(('Attribute (%s) ' % (attr_values[0])) +
'has no delimeter(:) and hence no value. Skipping...')
continue
if index:
value_pair = value_pair.replace('#', str(index))
if value_pair[0:3] == 'dn:':
if mod_list:
LDIF.write('changetype: add\n')
dn = value_pair
LDIF.write(value_pair + "\n")
return dn
#
# Read the tempalte file and store the template in the entry
#
def read_template(entry, member):
LDIF = None
if member:
if verbose:
print ('Opening template file: ' + entry['member_template_file'])
try:
LDIF = open(entry['member_template_file'], "r")
except IOError:
print ("Can\'t open template file: " + entry['template_file'])
exit(1)
entry['member_template'] = list(LDIF)
else:
if verbose:
print ('Opening template file: ' + entry['template_file'])
try:
LDIF = open(entry['template_file'], "r")
except IOError:
print ("Can\'t open template file: " + entry['template_file'])
exit(1)
entry['template'] = list(LDIF)
LDIF.close()
#
# Write the group template entries to LDIF
#
def write_group_template(LDIF, idx, group):
group_index = get_index(idx, group['entries'])
dn = process_attr_list(LDIF, group['template'], group_index)
# Add members to the group
member_idx = 1
while member_idx <= int(group['members']):
if 'member_template' in group:
member_value = \
group['member_template'][0].rstrip().replace('dn: ', '')
#member_value = member_value.rstrip()
if group['create_unique_members']:
index = ('_' + str(idx) + '_' +
get_index(member_idx, group['members']))
else:
index = get_index(member_idx, group['members'])
member_value = member_value.replace('#', index)
mdn = "%s: %s\n" % (group['member_attr'], member_value)
LDIF.write(mdn)
else:
member_value = group['member_name']
if group['create_unique_members']:
member_value = member_value + '_' + str(idx) + '_'
mdn = "%s: %s=%s%s,%s\n" % (group['member_attr'],
group['member_rdn'],
member_value,
get_index(member_idx, group['members']),
group['member_parent'])
LDIF.write(mdn)
if verbose:
print ('Adding ' + group['member_attr'] + ': ' + member_value +
'...')
member_idx += 1
if verbose:
print ('Created group: ' + dn.replace('dn: ', ''))
LDIF.write('\n')
#
# Write the template entries to LDIF
#
def write_template(LDIF, idx, entry, member=0, member_idx=0, mod_list=False):
# Start parsing the list
#
# Check for key words: RANDOM, RANDOM-INT
# Check for selection of random values: RANDOM-PICK: VALUE, VALUE, VALUE
#
if member:
template_entry = entry['member_template']
else:
template_entry = entry['template']
entry_index = get_index(idx, entry['entries'])
dn = process_attr_list(LDIF, template_entry, entry_index, mod_list)
LDIF.write('\n')
if verbose:
print ('Created entry: ' + dn.replace('dn: ', ''))
def write_parent_entry(LDIF, dn, skip_aci):
LDIF.write('dn: ' + dn + '\n')
LDIF.write('objectclass: top\n')
dn_parts = dn.split('=')
dn_values = dn_parts[1].split(',')
if dn_parts[0] == 'o':
LDIF.write('objectclass: organization\n')
LDIF.write('o: ' + dn_values[0] + '\n')
elif dn_parts[0] == 'dc':
LDIF.write('objectclass: domain\n')
LDIF.write('dc: ' + dn_values[0] + '\n')
elif dn_parts[0] == 'ou':
LDIF.write('objectclass: organizationalUnit\n')
LDIF.write('ou: ' + dn_values[0] + '\n')
elif dn_parts[0] == 'cn':
LDIF.write('objectclass: organizationalUnit\n')
LDIF.write('ou: ' + dn_values[0] + '\n')
LDIF.write('cn: ' + dn_values[0] + '\n')
else:
LDIF.write('objectclass: extensibleObject\n')
LDIF.write(dn_parts[0] + ': ' + dn_values[0] + '\n')
# add a default aci's
if not skip_aci:
LDIF.write('aci: (target=ldap:///' + dn + ')(targetattr=*)(version ' +
'3.0; acl "Self Write ACI for ' + dn + '"; allow(write) ' +
'userdn = "ldap:///self";)\n')
LDIF.write('aci: (target=ldap:///' + dn + ')(targetattr=*)(version ' +
'3.0; acl "Directory Admin ACI for ' + dn +
'"; allow(write) groupdn = "ldap:///cn=Directory ' +
'Administrators, dc=example,dc=com";)\n')
LDIF.write('aci: (target=ldap:///' + dn + ')(targetattr=*)(version ' +
'3.0; acl "Anonymous ACI for ' + dn + '"; allow(read, ' +
'search, compare) userdn = "ldap:///anyone";)\n')
LDIF.write('\n')
if verbose:
print ('Created branch entry: ' + dn)
#
# Write the parent entry, up to and including the base suffix
#
def write_parent(LDIF, parent_dn, suffix_dn, skip_aci, create_chart):
# do some basic normalization
parent_dn = parent_dn.replace(' ,', ',')
parent_dn = parent_dn.replace(', ', ',')
parent_dn.lower()
suffix_dn = suffix_dn.replace(' ,', ',')
suffix_dn = suffix_dn.replace(', ', ',')
suffix_dn.lower()
if parent_dn != suffix_dn:
suffix_parts = suffix_dn.split(',')
parent_parts = parent_dn.split(',')
suffix_len = len(suffix_parts)
parent_len = len(parent_parts)
position = len(parent_dn) - len(suffix_dn)
if parent_dn[position:] != suffix_dn:
print (('The parent DN (%s) and the suffix DN (%s) ' %
(parent_dn, suffix_dn)) + 'are not compatible. ' +
'Exiting...')
LDIF.close()
exit(1)
if (parent_len - suffix_len) == 1:
write_parent_entry(LDIF, suffix_dn, skip_aci)
if not skip_aci:
# we only need to write the default ACI's once
skip_aci = True
elif (parent_len - suffix_len) > 1:
# Write the suffix
write_parent_entry(LDIF, suffix_dn, skip_aci)
if not skip_aci:
# we only need to write the default ACI's once
skip_aci = True
# Write the filler branches between the suffix and parent DN's
while True:
# strip off the top branch
parent_parts = parent_parts[1:]
# build the DN
subsuffix = ''
for comp in parent_parts:
subsuffix = subsuffix + comp + ','
# remove the last comma
subsuffix = subsuffix[:-1]
if subsuffix == suffix_dn:
# we're done
break
write_parent_entry(LDIF, subsuffix, True)
elif suffix_len == parent_len:
# the dn's are the same length, but do not match!
print (('The parent DN (%s) and the suffix DN (%s) ' %
(parent_dn, suffix_dn)) + 'are not compatible. ' +
'Exiting...')
LDIF.close()
exit(1)
else:
print ("we should not be here!!")
write_parent_entry(LDIF, parent_dn, skip_aci)
if create_chart:
write_org_chart(LDIF, suffix_dn)
#
# Write the default entry attributes to the LDIF entry
#
def write_user_default_attrs(LDIF, user):
for attr in user_attrs:
if attr == 'description':
LDIF.write(attr + ': Description for ' + user['name'] + '\n')
elif attr == 'employeenumber':
LDIF.write(attr + ': ' + get_random_value("int", 6) + '\n')
elif attr == 'homephone':
LDIF.write(attr + ': ' + get_random_value("tele") + '\n')
elif attr == 'initials':
LDIF.write(attr + ': ' + str(user['uid'])[:2] + '\n')
elif attr == 'telephonenumber':
LDIF.write(attr + ': ' + get_random_value("tele") + '\n')
elif attr == 'facsimiletelephonenumber':
LDIF.write(attr + ': ' + get_random_value("tele") + '\n')
elif attr == 'mobile':
LDIF.write(attr + ': ' + get_random_value("tele") + '\n')
elif attr == 'pager':
LDIF.write(attr + ': ' + get_random_value("tele") + '\n')
elif attr == 'manager':
LDIF.write(attr + ': ' + get_manager(user) + '\n')
elif attr == 'secretary':
LDIF.write(attr + ': ' + get_random_value("secretary") + ',' +
user['suffix'] + '\n')
elif attr == 'roomnumber':
LDIF.write(attr + ': ' + get_random_value("int", 5) + '\n')
elif attr == 'carlicense':
LDIF.write(attr + ': ' + get_random_value("alpha", 7) + '\n')
elif attr == 'l':
LDIF.write(attr + ': ' + random_pick(localities) + '\n')
elif attr == 'mail':
LDIF.write(attr + ': ' + get_email_address(user) + '\n')
elif attr == 'postaladdress':
LDIF.write(attr + ': ' + user['suffix'] + ' Dept #' +
str(random.randomint(1, 25)) + ', Room#' +
str(random.randomint(1, 1000)) + '\n')
elif attr == 'title':
LDIF.write(attr + ': ' + random_pick(titles) + '\n')
elif attr == 'usercertificate;binary':
LDIF.write("usercertificate;binary:: MIIBvjCCASegAwIBAgIBAjANBgk" +
"qhkiG9w0BAQQFADAnMQ8wDQYD\n VQQDEwZjb25maWcxFDASBgNV" +
"BAMTC01NUiBDQSBDZXJ0MB4XDTAxMDQwNTE1NTEwNloXDTExMDcw" +
"\n NTE1NTEwNlowIzELMAkGA1UEChMCZnIxFDASBgNVBAMTC01NU" +
"iBTMSBDZXJ0MIGfMA0GCSqGSIb3\n DQEBAQUAA4GNADCBiQKBgQ" +
"DNlmsKEaPD+o3mAUwmW4E40MPs7aiui1YhorST3KzVngMqe5PbOb" +
"UH\n MeJN7CLbq9SjXvdB3y2AoVl/s5UkgGz8krmJ8ELfUCU95AQ" +
"ls321RwBdLRjioiQ3MGJiFjxwYRIV\n j1CUTuX1y8dC7BWvZ1/E" +
"B0yv0QDtp2oVMUeoK9/9sQIDAQABMA0GCSqGSIb3DQEBBAUAA4GB" +
"ADev\n hxY6QyDMK3Mnr7vLGe/HWEZCObF+qEo2zWScGH0Q+dAmh" +
"kCCkNeHJoqGN4NWjTdnBcGaAr5Y85k1\n o/vOAMBsZePbYx4Sry" +
"wL0b/OkOmQX+mQwieC2IQzvaBRyaNMh309vrF4w5kExReKfjR/gX" +
"pHiWQz\n GSxC5LeQG4k3IP34\n")
#
# Build a DN value, make it "unnormalized" if so requested.
# Return the DN and the new rdn value
#
def get_dn(rdn, name, parent, unnorm):
if unnorm:
return (rdn.upper() + ' = ' + name +
'\"cN=unNormaL, ou=iZED\, z="\, , ' +
parent), (name + '\"cN=unNormaL, ou=iZED\, z="\,')
else:
return (rdn + '=' + name + ',' + parent), name
#
# Get the domain from the suffix
#
def get_domain(suffix):
dc_parts = suffix.split(',')
return '.'.join([part.replace('dc=', '') for part in dc_parts])
#
# Bloat the entry size
#
# If the entry is not are large as the requested size then increase it.
# Use multiple description attributes
#
def bloat_entry(LDIF, final_size):
curr_size = LDIF.tell()
if curr_size + 15 < final_size:
remainder = final_size - curr_size
while remainder:
if remainder > 1024:
LDIF.write('description: ' + get_random_value('alphanum', 1010) +
'\n')
remainder -= 1024
else:
LDIF.write('description: ' +
get_random_value('alphanum', (remainder - 15)) + '\n')
remainder = 0
#
# Write IPA User entries to LDIF
#
def write_ipa_users(LDIF, user):
idx = 1
user['parent'] = 'cn=users,cn=accounts,' + user['suffix']
while idx <= int(user['entries']):
if not user['name']:
# Use real names
user['givenname'] = random_pick(firstnames)
user['sn'] = random_pick(lastnames)
user['cn'] = user['givenname'] + ' ' + user['sn']
user['uid'] = user['givenname'][0] + user['sn'] + str(idx)
user['dnval'] = user['uid']
else:
# Use ldclt naming convention
user['givenname'] = get_random_value("alpha")
user['sn'] = get_random_value("alpha")
user['cn'] = user['givenname'] + ' ' + user['sn']
user['uid'] = user['name'] + get_index(idx, user['entries'])
user['dnval'] = user['uid']
(name_dn, rdn) = get_dn('uid', user['dnval'], user['parent'],
user['unnorm'])
# Write the entry
LDIF.write(f'dn: {name_dn}\n')
# objectclasses
LDIF.write('objectclass: top\n')
LDIF.write('objectclass: person\n')
LDIF.write('objectclass: inetorgperson\n')
LDIF.write('objectclass: organizationalPerson\n')
LDIF.write('objectclass: inetUser\n')
LDIF.write('objectclass: posixaccount\n')
LDIF.write('objectclass: krbprincipalaux\n')
LDIF.write('objectclass: krbticketpolicyaux\n')
LDIF.write('objectclass: ipaobject\n')
LDIF.write('objectclass: ipasshuser\n')
LDIF.write('objectclass: ipaSshGroupOfPubKeys\n')
LDIF.write('objectclass: mepOriginEntry\n')
# LDIF.write('objectClass: ipantuserattrs\n')
# attrs
LDIF.write(f"uid: {user['uid']}\n")
LDIF.write(f"cn: {user['cn']}\n")
LDIF.write(f"sn: {user['sn']}\n")
LDIF.write(f"givenname: {user['givenname']}\n")
# posix attrs
LDIF.write(f"displayName: {user['cn']}\n")
LDIF.write(f"initials: {str(user['uid'])[:2].upper()}\n")
LDIF.write(f"gecos: {user['cn']}\n")
LDIF.write(f"loginShell: /bin/sh\n")
LDIF.write(f"homeDirectory: /home/{user['uid']}\n")
LDIF.write(f"uidNumber: {(idx + 1)}\n")
LDIF.write(f"gidNumber: {(idx + 1)}\n")
LDIF.write(f"mail: {user['uid']}@{get_domain(user['suffix'])}\n")
realm = get_domain(user['suffix']).upper()
LDIF.write(f"krbPrincipalName: {user['uid']}@{realm}\n")
LDIF.write(f"krbCanonicalName: {user['uid']}@{realm}\n")
if user['passwd'] == '':
passwd = user['dnval']
else:
passwd = user['passwd']
LDIF.write(f'userpassword: {passwd}\n')
# custom values
process_attr_list(LDIF, user['schema'], idx)
if verbose:
print('Created IPA user entry: ' + name_dn)
LDIF.write('\n')
idx += 1
#
# Interactive IPA User Entry Creation
#
def create_ipa_users():
global padding
user = {
'schema': [],
'create_parent': False,
'createorgchart': False,
'skip_aci': True,
'unnorm': False
}
print ('\nCreate Users')
user['entries'] = 'invalid'
while not user['entries'].isdigit():
user['entries'] = input(' Number of user entries [10000]: ')
if user['entries'] == '':
user['entries'] = '10000'
user['name'] = input(' Enter user name or press ENTER to use ' +
'"real names": ')
user['passwd'] = input(' Enter userpassword value (default is the ' +
'user\'s "uid" value): ')
user['suffix'] = input(' Enter base suffix DN [dc=example,dc=com]: ')
if user['suffix'] == '':
user['suffix'] = 'dc=example,dc=com'
custom_schema = input(' Add additional attributes [n]: ')
if custom_schema == 'y':
print (' Enter \"attribute: value\", press Enter when finished. ')
while True:
value_pair = input(' Attr/Value: ')
if value_pair == '':
break
user['schema'].append(value_pair)
user['size'] = 0
LDIF = open_ldif(None)
write_ipa_users(LDIF, user)
LDIF.close()
print ('Done.')
def write_ipa_hosts(LDIF, host):
domain_comps = host['fqdn'].split('.')
hostname = domain_comps.pop(0)
domain = '.'.join(domain_comps)
idx = 1
while idx <= int(host['entries']):
# Write the entry
host_name = hostname + str(idx)
fqdn = f"{host_name}.{domain}"
LDIF.write(f"dn: fqdn={fqdn},cn=computers,cn=accounts,{host['suffix']}\n")
LDIF.write('objectClass: top\n')
LDIF.write('objectClass: ipaobject\n')
LDIF.write('objectClass: nshost\n')
LDIF.write('objectClass: ipahost\n')
LDIF.write('objectClass: ipaservice\n')
LDIF.write('objectClass: pkiuser\n')
LDIF.write('objectClass: krbprincipalaux\n')
LDIF.write('objectClass: krbprincipal\n')
LDIF.write('objectClass: krbticketpolicyaux\n')
LDIF.write('objectClass: ipasshhost\n')
LDIF.write('objectClass: ipaSshGroupOfPubKeys\n')
LDIF.write(f"fqdn: {fqdn}\n")
LDIF.write(f"cn: {fqdn}\n")
LDIF.write(f"serverHostName: {host_name}\n")
realm = get_domain(host['suffix']).upper()
LDIF.write(f"krbPrincipalName: host/{fqdn}@{realm}\n")
LDIF.write(f"krbCanonicalName: host/{fqdn}@{realm}\n")
# process custom attributes
process_attr_list(LDIF, host['schema'], idx)
if verbose:
print('Created host entry: ' + name_dn)
LDIF.write('\n')
idx += 1
def create_ipa_hosts():
print('\nCreate Users')
host = {
'schema': [],
'entries': 'invalid'
}
while not host['entries'].isdigit():
host['entries'] = input(' Number of host entries [1000]: ')
if host['entries'] == '':
host['entries'] = '1000'
host['fqdn'] = input(' Enter FQDN: ')
host['suffix'] = input(' Enter base suffix DN [dc=example,dc=com]: ')
if host['suffix'] == '':
host['suffix'] = 'dc=example,dc=com'
custom_schema = input(' Add additional attributes [n]: ')
if custom_schema == 'y':
print (' Enter \"attribute: value\", press Enter when finished. ')
while True:
value_pair = input(' Attr/Value: ')
if value_pair == '':
break
host['schema'].append(value_pair)
LDIF = open_ldif(None)
write_ipa_hosts(LDIF, host)
LDIF.close()
print ('Done.')
#
# Write user entries to LDIF
#
def write_users(LDIF, user, mod_list=False):
idx = 1
if user['create_parent']:
write_parent(LDIF, user['parent'], user['suffix'], user['skip_aci'],
user['createorgchart'])
while idx <= int(user['entries']):
if 'template' in user:
write_template(LDIF, idx, user, 0, 0, mod_list)
else:
print_rdn = False
if not user['name']:
# Use real names
user['givenname'] = random_pick(firstnames)
user['sn'] = random_pick(lastnames)
user['cn'] = user['givenname'] + ' ' + user['sn']
user['uid'] = str(user['givenname'])[:1] + str(user['sn'])[:]
if user['rdn'] == 'cn':
user['cn'] = user['cn'] + str(idx)
user['dnval'] = user['cn']
elif user['rdn'] == 'uid':
user['uid'] = user['uid'] + str(idx)
user['dnval'] = user['uid']
else:
print_rdn = True
user['dnval'] = user['uid'] + str(idx)
else:
# Use ldclt naming convention
user['givenname'] = get_random_value("alpha")
user['sn'] = get_random_value("alpha")
user['cn'] = user['givenname'] + ' ' + user['sn']
user['uid'] = user['name'] + get_index(idx, user['entries'])
if user['rdn'] == 'cn':
user['cn'] = user['cn'] + get_index(idx, user['entries'])
user['dnval'] = user['cn']
elif user['rdn'] == 'uid':
user['dnval'] = user['uid']
else:
print_rdn = True
user['dnval'] = user['uid'] + str(idx)
(name_dn, rdn) = get_dn(user['rdn'], user['dnval'], user['parent'],
user['unnorm'])
if user['rdn'] == 'cn':
user['cn'] = rdn
elif user['rdn'] == 'uid':
user['uid'] = rdn
# Write the entry
LDIF.write('dn: ' + name_dn + '\n')
if mod_list:
LDIF.write('changetype: add\n')
LDIF.write('objectclass: top\n')
LDIF.write('objectclass: person\n')
LDIF.write('objectclass: inetorgperson\n')
LDIF.write('objectclass: organizationalPerson\n')
LDIF.write('objectclass: inetUser\n')
if print_rdn:
LDIF.write(user['rdn'] + ": " + rdn + '\n')
LDIF.write('uid: ' + user['uid'] + '\n')
LDIF.write('cn: ' + user['cn'] + '\n')
LDIF.write('sn: ' + user['sn'] + '\n')
LDIF.write('givenname: ' + user['givenname'] + '\n')
process_attr_list(LDIF, user['schema'], idx)
# write the remaining default attribute
write_user_default_attrs(LDIF, user)
if user['passwd'] == '':
passwd = user['dnval']
else:
passwd = user['passwd']
LDIF.write('userpassword: ' + passwd + '\n')
# bloat the entry size if requested
if user['size']:
bloat_entry(LDIF, int(user['size']))
if verbose:
print ('Created user entry: ' + name_dn)
LDIF.write('\n')
idx += 1
#
# Interactive User Entry Creation
#
def create_users():
global padding
user = {
'schema': [],
'create_parent': False,
'createorgchart': False,
'skip_aci': True,
'unnorm': False