-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathvmam.py
2068 lines (1772 loc) · 87.4 KB
/
vmam.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/env python3
# -*- encoding: utf-8 -*-
# vim: se ts=4 et syn=python:
# created by: matteo.guadrini
# vmam -- vmam
#
# Copyright (C) 2019 Matteo Guadrini <[email protected]>
#
# 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 3 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.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
VLAN Mac-address Authentication Manager
vmam is a command line tool which allows the management and maintenance of the mac-addresses
that access the network under a specific domain and a specific VLAN, through LDAP authentication.
This is based on RFC-3579(https://tools.ietf.org/html/rfc3579#section-2.1).
Usage for command line:
SYNOPSYS
.. code-block:: console
vmam [action] [parameter] [options]
config {action}: Configuration command for vmam environment
--new/-n {parameter}: Instruction to create a new configuration file. By specifying a path, it creates the
file in the indicated path. The default path is /etc/vmam/vmam.cfg
$> vmam config --new
Create a new configuration in a standard path: /etc/vmam/vmam.cfg
--get-cmd/-g {parameter}: Instruction to obtain the appropriate commands to configure your network
infrastructure and radius server around the created configuration file. By specifying a path, get
the file in the indicated path. The default path is /etc/vmam/vmam.cfg
$> vmam config --get-cmd
It takes instructions to configure its own network and radius server structure,
from standard path: /etc/vmam/vmam.cfg
start {action}: Automatic action for vmam environment
--config-file/-c {parameter}: Specify a configuration file in a custom path (optional)
$> vmam start --config-file /home/arthur/vmam.cfg
Start automatic process based on custom path configuration file: /home/arthur/vmam.cfg
--daemon/-d {parameter}: If specified, the automatic process run in background
$> vmam start --daemon
Start automatic process in background based on standard path: /etc/vmam/vmam.cfg
mac {action}: Manual action for adding, modifying, deleting and disabling of the mac-address users
--add/-a {parameter}: Add a specific mac-address on LDAP with specific VLAN. See also --vlan-id/-i
$> vmam mac --add 000018ff12dd --vlan-id 110
Add new mac-address user with VLAN 110, based on standard configuration file: /etc/vmam/vmam.cfg
$> vmam mac --add 000018ff12dd --vlan-id 111
Modify new or existing mac-address user with VLAN 111, based on standard configuration
file: /etc/vmam/vmam.cfg
--description/-D {parameter}: Add description on created mac-address
$> vmam mac --add 000018ff12dd --vlan-id 110 --description "My personal linux"
Add new mac-address user with VLAN 110, based on standard configuration file: /etc/vmam/vmam.cfg
--remove/-r {parameter}: Remove a mac-address user on LDAP
$> vmam mac --remove 000018ff12dd
Remove mac-address user 000018ff12dd, based on standard configuration file: /etc/vmam/vmam.cfg
--disable/-d {parameter}: Disable a mac-address user on LDAP, without removing
$> vmam mac --disable 000018ff12dd
Disable mac-address user 000018ff12dd, based on standard configuration file: /etc/vmam/vmam.cfg
--force/-f {parameter}: Force remove/disable action
$> vmam mac --remove 000018ff12dd --force
Force remove mac-address user 000018ff12dd, based on standard configuration file: /etc/vmam/vmam.cfg
--vlan-id/-i {parameter}: Specify a specific VLAN-id
$> vmam mac --add 000018ff12dd --vlan-id 100
Add new mac-address user with VLAN 100, based on standard configuration file: /etc/vmam/vmam.cfg
--config-file/-c {parameter}: Specify a configuration file in a custom path (optional)
$> vmam mac --remove 000018ff12dd --config-file /opt/vlan-office/office.cfg
Remove mac-address user 000018ff12dd, based on custom configuration file: /opt/vlan-office/office.cfg
--version/-V {option}: Print version and exit
--verbose/-v {option}: Print and log verbose information, for debugging
Usage like a module:
.. code-block:: python
#!/usr/bin/env python3
from vmam import *
# activate debug
debug = True
# define log writer
wt = logwriter('/tmp/log.log')
# start script
debugger(debug, wt, 'Start...')
# connect to LDAP server
conn = connect_ldap(['dc1.foo.bar'])
bind = bind_ldap(conn, r'domain\\admin', 'password', tls=True)
ldap_version = check_ldap_version(bind, 'dc=foo,dc=bar')
for mac in get_mac_from_file('/tmp/mac_list.txt'):
debugger(debug, wt, 'create mac address {}'.format(mac))
# create mac address
dn = 'cn={},ou=mac,dc=foo,dc=bar'.format(mac)
attrs = {'givenname': 'mac-address',
'sn': mac,
'samaccountname': mac
}
# create mac-address user
new_user(bind, dn, **attrs)
# add mac user to vlan group
add_to_group(bind, 'cn=vlan_group100,ou=groups,dc=foo,dc=bar', dn)
# set password and password never expires
set_user(bind, dn, pwdlastset=-1, useraccountcontrol=66048)
set_user_password(bind, dn, mac, ldap_version=ldap_version)
AUTHOR
Matteo Guadrini <[email protected]>
COPYRIGHT
(c) Matteo Guadrini. All rights reserved.
"""
# region Import dependencies
import daemon
import ldap3
import winrm
import yaml
# endregion
# region Imports
import os
import sys
import time
import socket
import logging
import argparse
import datetime
# endregion
# region Function for check dependencies module are installed
def check_module(module):
"""
This function checks if a module is installed.
:param module: The name of the module you want to check
:return: Boolean
---
>>>check_module('os')
True
"""
return module in sys.modules
# endregion
# region Global variable
VERSION = '1.4.4'
__all__ = ['logwriter', 'debugger', 'confirm', 'read_config', 'get_platform', 'new_config', 'bind_ldap',
'check_connection', 'check_config', 'connect_ldap', 'unbind_ldap', 'query_ldap', 'check_ldap_version',
'new_user', 'set_user', 'delete_user', 'set_user_password', 'add_to_group', 'remove_to_group',
'filetime_to_datetime', 'datetime_to_filetime', 'get_time_sync', 'string_to_datetime', 'format_mac',
'connect_client', 'run_command', 'get_mac_address', 'get_client_user', 'check_vlan_attributes', 'VERSION',
'get_mac_from_file', 'timestamp_to_datetime', 'datetime_to_timestamp']
bind_start = False
# endregion
# region Functions
def printv(*messages):
"""
Print verbose information
:param messages: List of messages
:return: String print on stdout
.. testcode::
>>> printv('Test','printv')
"""
print("DEBUG:", *messages)
def logwriter(logfile):
"""
Logger object than write line in a log file
:param logfile: Path of logfile(.log)
:return: Logger object
.. testcode::
>>> wl = logwriter('test.log')
>>> wl.info('This is a test')
"""
# Create logging object
_format = logging.Formatter('%(asctime)s %(levelname)-4s %(message)s')
# Folder exists?
leaf = os.path.split(logfile)
if not os.path.exists(leaf[0]):
try:
os.makedirs(leaf[0])
except Exception as err:
print('ERROR: {0}'.format(err))
exit(2)
try:
handler = logging.FileHandler(logfile)
handler.setFormatter(_format)
logger = logging.getLogger(os.path.basename(__file__))
logger.setLevel(logging.DEBUG)
if not len(logger.handlers):
logger.addHandler(handler)
return logger
except Exception as err:
print('ERROR: {0}'.format(err))
exit(2)
def debugger(verbose, writer, message):
"""
Debugger: write debug and print verbose message
:param verbose: verbose status; boolean
:param writer: Log writer object
:param message: String message
:return: String on stdout
.. testcode::
>>> wl = logwriter('test.log')
>>> debugger(True, wl, 'Test debug')
"""
if verbose:
writer.debug(message)
printv(message)
def confirm(message):
"""
Confirm action
:param message: Question that expects a 'yes' or 'no' answer
:return: Boolean
.. testcode::
>>> if confirm('Please, respond'):
... print('yep!')
"""
# Question
question = message + ' [Y/n]: '
# Possible right answers
yes = ['yes', 'y', 'ye', '']
no = ['no', 'n']
# Validate answer
choice = input(question).lower()
while True:
if choice in yes:
return True
elif choice in no:
return False
# I do not understand
print("Please, respond with 'yes' or 'no'")
# Validate answer
choice = input(question).lower()
def read_config(path):
"""
Open YAML configuration file
:param path: Path of configuration file
:return: Python object
.. testcode::
>>> cfg = read_config('/tmp/vmam.yml')
>>> print(cfg)
"""
try:
with open('{0}'.format(path)) as file:
return yaml.full_load(file)
except FileNotFoundError as err:
print('ERROR: {0}'.format(err))
exit(3)
except OSError as err:
print('ERROR: {0}'.format(err))
exit(2)
def write_config(obj, path):
"""
Write YAML configuration file
:param obj: Python object that will be converted to YAML
:param path: Path of configuration file
:return: None
.. testcode::
>>> write_config(obj, '/tmp/vmam.yml')
"""
with open('{0}'.format(path), 'w') as file:
yaml.dump(obj, file)
def get_mac_from_file(path, mac_format='none'):
"""
Get mac-address from file list
:param path: Path of file list. Mac-address can write in any format.
file example (/tmp/list.txt):
112233445566\n
# mac of my Linux\n
11-22-33-44-55-66\n
# this macs is\n
# other pc of my office\n
\n
11:22:33:44:55:66\n
1122.3344.5566\n
:param mac_format: mac format are (default=none):
none 112233445566\n
hypen 11-22-33-44-55-66\n
colon 11:22:33:44:55:66\n
dot 1122.3344.5566\n
:return: list
.. testcode::
>>> get_mac_from_file('/tmp/list')
"""
macs = list()
f = open(path)
# Support empty line
lines = [line.strip() for line in f if line.strip()]
for line in lines:
mac = line.strip()
# Support comment line
if not mac.startswith('#'):
macs.append(format_mac(mac, mac_format))
return macs
def get_platform():
"""
Get a platform (OS info)
:return: Platform info dictionary
.. testcode::
>>> p = get_platform()
>>> print(p)
"""
# Create os info object
os_info = {'conf_default': '/etc/vmam/vmam.yml', 'log_default': '/var/log/vmam/vmam.log'}
return os_info
def new_config(path=(get_platform()['conf_default'])):
"""
Create a new vmam config file (YAML)
:param path: Path of config file
:return: None
.. testcode::
>>> new_config('/tmp/vmam.yml')
"""
# Folder exists?
leaf = os.path.split(path)
if not os.path.exists(leaf[0]):
try:
os.makedirs(leaf[0])
except Exception as err:
print('ERROR: {0}'.format(err))
exit(2)
conf = {
'LDAP': {
'servers': ['dc1', 'dc2'],
'domain': 'foo.bar',
'ssl': 'true|false',
'tls': 'true|false',
'bind_user': 'vlan_user',
'bind_pwd': 'secret',
'user_base_dn': 'DC=foo,DC=bar',
'computer_base_dn': 'DC=foo,DC=bar',
'mac_user_base_dn': 'OU=mac-users,DC=foo,DC=bar',
'mac_user_ttl': '365d',
'time_computer_sync': '1m',
'verify_attrib': ['memberof', 'cn'],
'write_attrib': 'extensionattribute1',
'match': 'like|exactly',
'add_group_type': ['user', 'computer'],
'other_group': ['second_grp', 'third_grp']
},
'VMAM': {
'mac_format': 'none|hypen|colon|dot',
'soft_deletion': 'true|false',
'filter_exclude': ['list1', 'list2'],
'log': get_platform()['log_default'],
'automatic_process_wait': 3,
'black_list': '',
'remove_process': True,
'user_match_id': {
'value1': 100,
'value2': 101
},
'vlan_group_id': {
100: 'group1',
101: 'group2'
},
'winrm_user': 'admin',
'winrm_pwd': 'secret'
}
}
write_config(conf, path)
def check_connection(ip, port, timeout=3):
"""
Test connection of remote (ip) machine on (port)
:param ip: ip address or hostname of machine
:param port: tcp port
:param timeout: set timeout of connection
:return: Boolean
.. testcode::
>>> check_connection('localhost', 80)
"""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.settimeout(timeout)
s.connect((ip, port))
s.shutdown(socket.SHUT_RDWR)
return True
except socket.error:
return False
def check_config(path):
"""
Check YAML configuration file
:param path: Path of configuration file
:return: Boolean
.. testcode::
>>> cfg = check_config('/tmp/vmam.yml')
"""
# Check exists configuration file
assert os.path.exists(path), 'Configuration file not exists: {0}'.format(path)
# Read the config file
config = read_config(path)
# Check the two principal configuration: LDAP and VMAM
assert 'LDAP' in config, 'Key "LDAP" is required!'
assert 'VMAM' in config, 'Key "VMAM" is required!'
assert len(config.keys()) == 2, 'The principal keys of configuration file are two: "LDAP" and "VMAM"!'
# Now, check mandatory fields of LDAP section
assert ('servers' in config['LDAP'] and len(config['LDAP']['servers']) > 0), 'Required LDAP:servers: field!'
assert ('domain' in config['LDAP'] and config['LDAP']['domain']), 'Required LDAP:domain: field!'
assert ('bind_user' in config['LDAP'] and config['LDAP']['bind_user']), 'Required LDAP:bind_user: field!'
assert ('bind_pwd' in config['LDAP'] and config['LDAP']['bind_pwd']), 'Required LDAP:bind_pwd: field!'
assert ('user_base_dn' in config['LDAP'] and config['LDAP']['user_base_dn']), 'Required LDAP:user_base_dn: field!'
assert ('computer_base_dn' in config['LDAP'] and
config['LDAP']['computer_base_dn']), 'Required LDAP:computer_base_dn: field!'
assert ('mac_user_base_dn' in config['LDAP'] and
config['LDAP']['mac_user_base_dn']), 'Required LDAP:mac_user_base_dn: field!'
assert ('verify_attrib' in config['LDAP'] and
len(config['LDAP']['verify_attrib']) > 0), 'Required LDAP:verify_attrib: field!'
assert ('match' in config['LDAP'] and config['LDAP']['match']), 'Required LDAP:match: field!'
assert ('add_group_type' in config['LDAP'] and
len(config['LDAP']['add_group_type']) > 0), 'Required LDAP:add_group_type: field!'
# Now, check mandatory fields of VMAM section
assert ('mac_format' in config['VMAM'] and config['VMAM']['mac_format']), 'Required VMAM:mac_format: field!'
assert ('soft_deletion' in config['VMAM'] and
config['VMAM']['soft_deletion']), 'Required VMAM:soft_deletion: field!'
assert ('automatic_process_wait' in config['VMAM'] and
isinstance(config['VMAM']['automatic_process_wait'], int)), 'Required VMAM:automatic_process_wait: field!'
assert ('user_match_id' in config['VMAM'] and
len(config['VMAM']['user_match_id'].keys()) > 0), 'Required VMAM:user_match_id: field!'
assert ('vlan_group_id' in config['VMAM'] and
len(config['VMAM']['vlan_group_id'].keys()) > 0), 'Required VMAM:vlan_group_id: field!'
# Check if value of user_match_id corresponding to keys of vlan_group_id
for k, v in config['VMAM']['user_match_id'].items():
assert config['VMAM']['vlan_group_id'].get(v), 'Theres is no correspondence between the key {0} ' \
'in vlan_group_id and the key {1} in user_match_id!'.format(v, k)
assert ('winrm_user' in config['VMAM'] and config['VMAM']['winrm_user']), 'Required VMAM:winrm_user: field!'
assert ('winrm_pwd' in config['VMAM'] and config['VMAM']['winrm_pwd']), 'Required VMAM:winrm_pwd: field!'
# Now, return ok (True)
return True
def connect_ldap(servers, *, ssl=False):
"""
Connect to LDAP server (SYNC mode)
:param servers: LDAP servers list
:param ssl: If True, set port to 636 else 389
:return: LDAP connection object
.. testcode::
>>> conn = connect_ldap(['dc1.foo.bar'], ssl=True)
>>> print(conn)
"""
# Check ssl connection
port = 636 if ssl else 389
# Create a server pool
srvs = list()
for server in servers:
srvs.append(ldap3.Server(server, get_info=ldap3.ALL, port=port, use_ssl=ssl))
# Start connection to LDAP server
server_connection = ldap3.ServerPool(srvs, ldap3.ROUND_ROBIN, active=True, exhaust=True)
return server_connection
def bind_ldap(server, user, password, *, tls=False):
"""
Bind with user a LDAP connection
:param server: LDAP connection object
:param user: user used for bind
:param password: password of user
:param tls: if True, start tls connection
:return: LDAP bind object
.. testcode::
>>> conn = connect_ldap(['dc1.foo.bar'])
>>> bind = bind_ldap(conn, r'domain\\user', 'password', tls=True)
>>> print(bind)
"""
auto_bind = ldap3.AUTO_BIND_TLS_BEFORE_BIND if tls else ldap3.AUTO_BIND_NONE
# Create a bind connection with user and password
bind_connection = ldap3.Connection(server, user='{0}'.format(user), password='{0}'.format(password),
auto_bind=auto_bind, raise_exceptions=True)
# Check LDAP bind connection
if bind_connection.bind():
return bind_connection
else:
print('Error in bind:', bind_connection.result)
def unbind_ldap(bind_object):
"""
Unbind LDAP connection
:param bind_object: LDAP bind object
:return: None
.. testcode::
>>> conn = connect_ldap(['dc1.foo.bar'])
>>> bind = bind_ldap(conn, r'domain\\user', 'password', tls=True)
>>> bind.unbind()
"""
# Disconnect LDAP server
bind_object.unbind()
def query_ldap(bind_object, base_search, attributes, comp='=', **filters):
"""
Query LDAP
:param bind_object: LDAP bind object
:param base_search: distinguishedName of LDAP base search
:param attributes: list of returning LDAP attributes
:param comp: comparison operator. Default is '='. Accepted:
Equality (attribute=abc) =
Negation (!attribute=abc) !
Presence (attribute=*) =*
Greater than (attribute>=abc) >=
Less than (attribute<=abc) <=
Proximity (attribute~=abc) ~=
:param filters: dictionary of ldap query
:return: query result list
.. testcode::
>>> conn = connect_ldap(['dc1.foo.bar'])
>>> bind = bind_ldap(conn, r'domain\\user', 'password', tls=True)
>>> ret = query_ldap(bind, 'dc=foo,dc=bar', ['sn', 'givenName'], objectClass='person', samAccountName='person1')
>>> print(ret)
"""
# Init query list
allow_comp = ['=', '>=', '<=', '~=', '=*', '!']
strict_comp = ['objectcategory', 'objectclass']
assert comp in allow_comp, "Comparison operator {0} is not allowed in LDAP query".format(comp)
query = ['(&']
# Build query
for key, value in filters.items():
if comp == '!':
query.append("(!{0}={1})".format(key, value))
else:
ncomp = '=' if key.lower() in strict_comp else comp
query.append("({0}{1}{2})".format(key, ncomp, value))
# Close query
query.append(')')
# Query!
if bind_object.search(search_base=base_search, search_filter=''.join(query), attributes=attributes,
search_scope=ldap3.SUBTREE):
return bind_object.response
def check_ldap_version(bind_object):
"""
Determines the LDAP version
:param bind_object: LDAP bind object
:return: LDAP version code: MS-LDAP or N-LDAP or LDAP
.. testcode::
>>> conn = connect_ldap(['dc1.foo.bar'])
>>> bind = bind_ldap(conn, r'domain\\user', 'password', tls=True)
>>> ret = check_ldap_version(bind)
>>> print(ret)
"""
# Microsoft LDAP
if 'MICROSOFT' in bind_object.server.info.supported_controls[0]:
return 'MS-LDAP'
# Novell LDAP
elif 'eDirectory' in bind_object.server.info.vendor_version:
return 'N-LDAP'
# Standard LDAP
else:
return 'LDAP'
def new_user(bind_object, username, **attributes):
"""
Create a new LDAP user
:param bind_object: LDAP bind object
:param username: distinguishedName of user
:param attributes: Dictionary attributes
:return: LDAP operation result
.. testcode::
>>> conn = connect_ldap(['dc1.foo.bar'])
>>> bind = bind_ldap(conn, r'domain\\user', 'password', tls=True)
>>> new_user(bind, 'CN=ex_user1,OU=User_ex,DC=foo,DC=bar', objectClass='user', givenName='User 1', sn='Example')
"""
# Create user
bind_object.add(
username,
attributes=attributes
)
return bind_object.result
def set_user(bind_object, username, **attributes):
"""
Modify an exists LDAP user
:param bind_object: LDAP bind object
:param username: distinguishedName of user
:param attributes: Dictionary attributes
:return: LDAP operation result
.. testcode::
>>> conn = connect_ldap(['dc1.foo.bar'])
>>> bind = bind_ldap(conn, r'domain\\user', 'password', tls=True)
>>> set_user(bind, 'CN=ex_user1,OU=User_ex,DC=foo,DC=bar', givenName='User 1', sn='Example')
"""
# Convert value to tuple
for key, value in attributes.items():
attributes[key] = (ldap3.MODIFY_REPLACE, value)
# Modify user
bind_object.modify(
username,
attributes
)
return bind_object.result
def delete_user(bind_object, username):
"""
Modify an exists LDAP user
:param bind_object: LDAP bind object
:param username: distinguishedName of user
:return: LDAP operation result
.. testcode::
>>> conn = connect_ldap(['dc1.foo.bar'])
>>> bind = bind_ldap(conn, r'domain\\user', 'password', tls=True)
>>> delete_user(bind, 'CN=ex_user1,OU=User_ex,DC=foo,DC=bar')
"""
bind_object.delete(username)
return bind_object.result
def set_user_password(bind_object, username, password, *, ldap_version='LDAP'):
"""
Set password to LDAP user
:param bind_object: LDAP bind object
:param username: distinguishedName of user
:param password: password to set of user
:param ldap_version: LDAP version (LDAP or MS-LDAP)
:return: None
.. testcode::
>>> conn = connect_ldap('dc1.foo.bar')
>>> bind = bind_ldap(conn, r'domain\\user', 'password', tls=True)
>>> new_user(bind, 'CN=ex_user1,OU=User_ex,DC=foo,DC=bar', givenName='User 1', sn='Example')
>>> set_user_password(bind, 'CN=ex_user1,OU=User_ex,DC=foo,DC=bar', 'password', ldap_version='MS-LDAP')
>>> set_user(bind, 'CN=ex_user1,CN=Users,DC=office,DC=bol', pwdLastSet=-1, userAccountControl=66048)
"""
# Set password
if ldap_version == 'LDAP':
bind_object.extend.standard.modify_password(username, new_password=password,
old_password=None)
elif ldap_version == 'MS-LDAP':
bind_object.extend.microsoft.modify_password(username, new_password=password, old_password=None)
elif ldap_version == 'N-LDAP':
bind_object.extend.NovellExtendedOperations.set_universal_password(username, new_password=password,
old_password=None)
else:
bind_object.extend.standard.modify_password(username, new_password=password,
old_password=None)
def add_to_group(bind_object, groupname, members):
"""
Add a member of exists LDAP group
:param bind_object: LDAP bind object
:param groupname: distinguishedName of group
:param members: List of a new members
:return: LDAP operation result
.. testcode::
>>> conn = connect_ldap('dc1.foo.bar')
>>> bind = bind_ldap(conn, r'domain\\user', 'password', tls=True)
>>> add_to_group(bind, 'CN=ex_group1,OU=Groups,DC=foo,DC=bar', 'CN=ex_user1,CN=Users,DC=office,DC=bol')
"""
# Modify group members
bind_object.modify(
groupname,
{'member': (ldap3.MODIFY_ADD, members)}
)
return bind_object.result
def remove_to_group(bind_object, groupname, members):
"""
Remove a member of exists LDAP group
:param bind_object: LDAP bind object
:param groupname: distinguishedName of group
:param members: List of a removed members
:return: LDAP operation result
.. testcode::
>>> conn = connect_ldap('dc1.foo.bar')
>>> bind = bind_ldap(conn, r'domain\\user', 'password', tls=True)
>>> remove_to_group(bind, 'CN=ex_group1,OU=Groups,DC=foo,DC=bar', 'CN=ex_user1,CN=Users,DC=office,DC=bol')
"""
# Modify group members
bind_object.modify(
groupname,
{'member': (ldap3.MODIFY_DELETE, members)}
)
return bind_object.result
def filetime_to_datetime(filetime):
"""
Convert MS filetime LDAP to datetime
:param filetime: filetime number (nanoseconds)
:return: datetime object
.. testcode::
>>> dt = filetime_to_datetime(132130209369676516)
>>> print(dt)
"""
# January 1, 1970 as MS filetime
epoch_as_filetime = 116444736000000000
us = (filetime - epoch_as_filetime) // 10
return datetime.datetime(1970, 1, 1) + datetime.timedelta(microseconds=us)
def datetime_to_filetime(date_time):
"""
Convert datetime to LDAP MS filetime
:param date_time: datetime object
:return: filetime number
.. testcode::
>>> ft = datetime_to_filetime(datetime.datetime(2001, 1, 1))
>>> print(ft)
"""
# January 1, 1970 as MS filetime
epoch_as_filetime = 116444736000000000
filetime = epoch_as_filetime + (int(date_time.timestamp())) * 10000000
return filetime + (date_time.microsecond * 10)
def timestamp_to_datetime(timestamp):
"""
Convert LDAP Kerberos timestamp LDAP to datetime
:param timestamp: kerberos timestamp string
:return: datetime object
.. testcode::
>>> dt = timestamp_to_datetime('20200903053604Z')
>>> print(dt)
"""
return datetime.datetime.strptime(timestamp, '%Y%m%d%H%M%S' + 'Z')
def datetime_to_timestamp(date_time):
"""
Convert datetime to LDAP Kerberos timestamp
:param date_time: datetime object
:return: kerberos timestamp string
.. testcode::
>>> ft = datetime_to_timestamp(datetime.datetime(1986, 1, 25))
>>> print(ft)
"""
return date_time.strftime('%Y%m%d%H%M%S' + 'Z')
def get_time_sync(timedelta):
"""
It takes the date for synchronization
:param timedelta: Time difference to subtract (string: 1s, 2m, 3h, 4d, 5w)
:return: datetime object
.. testcode::
>>> td = get_time_sync('1d')
>>> print(td)
"""
# Dictionary of units
units = {"s": "seconds", "m": "minutes", "h": "hours", "d": "days", "w": "weeks"}
# Extract info of timedelta
count = int(timedelta[:-1])
unit = units[timedelta[-1]]
delta = datetime.timedelta(**{unit: count})
# Calculate timedelta
return datetime.datetime.now() - delta
def string_to_datetime(string):
"""
Convert string date to datetime
:param string: Datetime in string format ('dd/mm/yyyy' or 'mm/dd/yyyy')
:return: Datetime object
.. testcode::
>>> dt = string_to_datetime('28/2/2019')
>>> print(dt)
"""
# Try convert 'dd/mm/yyyy'
try:
date = datetime.datetime.strptime(string, '%d/%m/%Y')
# return date object
return date
except ValueError:
pass
# Try convert 'mm/dd/yyyy'
try:
date = datetime.datetime.strptime(string, '%m/%d/%Y')
# return date object
return date
except ValueError:
return False
def format_mac(mac_address, mac_format='none'):
"""
Format mac-address with the specified format
:param mac_address: mac-address in any format
:param mac_format: mac format are (default=none):
none 112233445566\n
hypen 11-22-33-44-55-66\n
colon 11:22:33:44:55:66\n
dot 1122.3344.5566\n
:return: mac-address with the specified format
.. testcode::
>>> m = format_mac('1A2b3c4D5E6F', 'dot')
>>> print(m)
"""
# Set format
form = {
'none': lambda x: x.replace('.', '').replace('-', '').replace(':', '').lower(),
'hypen': lambda x: '-'.join([x[i:i + 2] for i in range(0, len(x), 2)]
).replace('.', '').replace(':', '').lower(),
'colon': lambda x: ':'.join([x[i:i + 2] for i in range(0, len(x), 2)]
).replace('.', '').replace('-', '').lower(),
'dot': lambda x: '.'.join([x[i:i + 4] for i in range(0, len(x), 4)]
).replace(':', '').replace('-', '').lower()
}
mac = form.get('none')(mac_address)
# Get format
try:
return form.get(mac_format)(mac)
except TypeError:
print('ERROR: "{0}" format not available. Available: "none", "hypen", "colon", "dot".'.format(mac_format))
return mac
def connect_client(client, user, password):
"""
Connect to client with WINRM protocol
:param client: hostname or ip address
:param user: username used for connection on client
:param password: password of user
:return: WINRM protocol object
.. testcode::