File: ldap.rst

package info (click to toggle)
python-ldap 3.4.4-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,756 kB
  • sloc: python: 9,558; ansic: 3,052; makefile: 139; sh: 79
file content (1471 lines) | stat: -rw-r--r-- 49,978 bytes parent folder | download | duplicates (2)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
********************************************
:py:mod:`ldap` LDAP library interface module
********************************************

.. py:module:: ldap
    :platform: Posix, Windows
    :synopsis: Access to an underlying LDAP C library.
.. moduleauthor:: python-ldap project (see https://www.python-ldap.org/)


This module provides access to the LDAP (Lightweight Directory Access Protocol)
C API implemented in OpenLDAP.  It is similar to the C API, with
the notable differences that lists are manipulated via Python list operations
and errors appear as exceptions.

   .. seealso::

      For more detailed information on the C interface, please see the (expired)
      `draft-ietf-ldapext-ldap-c-api <https://tools.ietf.org/html/draft-ietf-ldapext-ldap-c-api>`_


This documentation is current for the Python LDAP module, version
|release|.  Source and binaries are available from
https://www.python-ldap.org/.


Functions
=========

This module defines the following functions:

.. py:function:: initialize(uri [, trace_level=0 [, trace_file=sys.stdout [, trace_stack_limit=None, [fileno=None]]]]) -> LDAPObject object

   Initializes a new connection object for accessing the given LDAP server,
   and return an :class:`~ldap.ldapobject.LDAPObject` used to perform operations
   on that server.

   The *uri* parameter may be a comma- or whitespace-separated list of URIs
   containing only the schema, the host, and the port fields. Note that
   when using multiple URIs you cannot determine to which URI your client
   gets connected.

   If *fileno* parameter is given then the file descriptor will be used to
   connect to an LDAP server. The *fileno* must either be a socket file
   descriptor as :class:`int` or a file-like object with a *fileno()* method
   that returns a socket file descriptor. The socket file descriptor must
   already be connected. :class:`~ldap.ldapobject.LDAPObject` does not take
   ownership of the file descriptor. It must be kept open during operations
   and explicitly closed after the :class:`~ldap.ldapobject.LDAPObject` is
   unbound. The internal connection type is determined from the URI, ``TCP``
   for ``ldap://`` / ``ldaps://``, ``IPC`` (``AF_UNIX``) for ``ldapi://``.
   The parameter is not available on macOS when python-ldap is compiled with system
   libldap, see :py:const:`INIT_FD_AVAIL`.

   Note that internally the OpenLDAP function
   `ldap_initialize(3) <https://www.openldap.org/software/man.cgi?query=ldap_init&sektion=3>`_
   is called which just initializes the LDAP connection struct in the C API
   - nothing else. Therefore the first call to an operation method (bind,
   search etc.) then really opens the connection (lazy connect). Before
   that nothing is sent on the wire. The error handling in the calling
   application has to correctly handle this behaviour.

   Three optional arguments are for generating debug log information:
   *trace_level* specifies the amount of information being logged,
   *trace_file* specifies a file-like object as target of the debug log and
   *trace_stack_limit* specifies the stack limit of tracebacks in debug log.

   Possible values for *trace_level* are
   :py:const:`0` for no logging,
   :py:const:`1` for only logging the method calls with arguments,
   :py:const:`2` for logging the method calls with arguments and the complete results and
   :py:const:`9` for also logging the traceback of method calls.

   This function is a thin wrapper around instantiating
   :class:`~ldap.ldapobject.LDAPObject`.
   Any additional keyword arguments are passed to ``LDAPObject``.
   It is also fine to instantiate a ``LDAPObject`` (or a subclass) directly.

   The function additionally takes *bytes_mode* and *bytes_strictness* keyword
   arguments, which are deprecated and ignored. See :ref:`bytes_mode` for
   details.

   .. seealso::

      :rfc:`4516` - Lightweight Directory Access Protocol (LDAP): Uniform Resource Locator

   .. versionadded:: 3.3

      The *fileno* argument was added.

   .. deprecated:: 3.4

      *bytes_mode* and *bytes_strictness* arguments are deprecated.


.. py:function:: get_option(option) -> int|string

   This function returns the value of the global option specified by *option*.


.. py:function:: set_option(option, invalue) -> None

   This function sets the value of the global option specified by *option* to
   *invalue*.

   .. note::

      Most global settings do not affect existing :py:class:`LDAPObject`
      connections. Applications should call :py:func:`set_option()` before
      they establish connections with :py:func:`initialize`.

.. versionchanged:: 3.1

   The deprecated functions ``ldap.init()`` and ``ldap.open()`` were removed.


.. _ldap-constants:

Constants
=========

The module defines various constants. Note that some constants depend
on the build options and which underlying libs were used or even on
the version of the libs. So before using those constants the application has
to explicitly check whether they are available.

General
-------

.. py:data:: PORT

   The assigned TCP port number (389) that LDAP servers listen on.

.. py:data:: SASL_AVAIL

   Integer where a non-zero value indicates that python-ldap was built with
   support for SASL (Cyrus-SASL).

.. py:data:: TLS_AVAIL

   Integer where a non-zero value indicates that python-ldap was built with
   support for SSL/TLS (OpenSSL or similar libs).

.. py:data:: INIT_FD_AVAIL

   Integer where a non-zero value indicates that python-ldap supports
   :py:func:`initialize` from a file descriptor. The feature is generally
   available except on macOS when python-ldap is compiled with system libldap.


.. _ldap-options:

Options
-------

.. seealso::

   :manpage:`ldap.conf(5)` and :manpage:`ldap_get_option(3)`


For use with functions :py:func:`set_option` and :py:func:`get_option` and
methods :py:meth:`LDAPObject.set_option` and :py:meth:`LDAPObject.get_option`
the following option identifiers are defined as constants:

.. py:data:: OPT_API_FEATURE_INFO

.. py:data:: OPT_API_INFO

.. py:data:: OPT_CLIENT_CONTROLS

.. py:data:: OPT_DEBUG_LEVEL

   Sets the debug level within the underlying OpenLDAP C lib (libldap).
   libldap sends the log messages to stderr.

.. py:data:: OPT_DEFBASE

.. py:data:: OPT_DEREF

   Specifies how alias dereferencing is done within the underlying LDAP C lib.

.. py:data:: OPT_ERROR_STRING

.. py:data:: OPT_DIAGNOSTIC_MESSAGE

.. py:data:: OPT_HOST_NAME

.. py:data:: OPT_MATCHED_DN

.. py:data:: OPT_NETWORK_TIMEOUT

   .. versionchanged:: 3.0
      A timeout of ``-1`` or ``None`` resets timeout to infinity.

.. py:data:: OPT_PROTOCOL_VERSION

   Sets the LDAP protocol version used for a connection. This is mapped to
   object attribute `ldap.LDAPObject.protocol_version`

.. py:data:: OPT_REFERRALS

   int specifying whether referrals should be automatically chased within
   the underlying LDAP C lib.

.. py:data:: OPT_REFHOPLIMIT

.. py:data:: OPT_RESTART

.. py:data:: OPT_SERVER_CONTROLS

.. py:data:: OPT_SIZELIMIT

.. py:data:: OPT_SUCCESS

.. py:data:: OPT_TIMELIMIT

.. py:data:: OPT_TIMEOUT

   .. versionchanged:: 3.0
      A timeout of ``-1`` or ``None`` resets timeout to infinity.

.. py:data:: OPT_URI

.. _ldap-sasl-options:

SASL options
::::::::::::

Unlike most other options, SASL options must be set on an
:py:class:`LDAPObject` instance.

.. py:data:: OPT_X_SASL_AUTHCID

.. py:data:: OPT_X_SASL_AUTHZID

.. py:data:: OPT_X_SASL_MECH

.. py:data:: OPT_X_SASL_NOCANON

   If set to zero, SASL host name canonicalization is disabled.

.. py:data:: OPT_X_SASL_REALM

.. py:data:: OPT_X_SASL_SECPROPS

.. py:data:: OPT_X_SASL_SSF

.. py:data:: OPT_X_SASL_SSF_EXTERNAL

.. py:data:: OPT_X_SASL_SSF_MAX

.. py:data:: OPT_X_SASL_SSF_MIN

.. _ldap-tls-options:

TLS options
:::::::::::

.. warning::

   libldap does not materialize all TLS settings immediately. You must use
   :py:const:`OPT_X_TLS_NEWCTX` with value ``0`` to instruct libldap to
   apply pending TLS settings and create a new internal TLS context::

      conn = ldap.initialize("ldap://ldap.example")
      conn.set_option(ldap.OPT_X_TLS_CACERTFILE, '/path/to/ca.pem')
      conn.set_option(ldap.OPT_X_TLS_NEWCTX, 0)
      conn.start_tls_s()
      conn.simple_bind_s(dn, password)


.. py:data:: OPT_X_TLS_NEWCTX

   set and apply TLS settings to internal TLS context. Value ``0`` creates
   a new client-side context.

.. py:data:: OPT_X_TLS_PACKAGE

   Get TLS implementation, known values are

   * ``GnuTLS``
   * ``MozNSS`` (Mozilla NSS)
   * ``OpenSSL``


.. py:data:: OPT_X_TLS_CACERTDIR

   get/set path to directory with CA certs

.. py:data:: OPT_X_TLS_CACERTFILE

   get/set path to PEM file with CA certs

.. py:data:: OPT_X_TLS_CERTFILE

   get/set path to file with PEM encoded cert for client cert authentication,
   requires :py:const:`OPT_X_TLS_KEYFILE`.

.. py:data:: OPT_X_TLS_KEYFILE

   get/set path to file with PEM encoded key for client cert authentication,
   requires :py:const:`OPT_X_TLS_CERTFILE`.


.. py:data:: OPT_X_TLS_CRLCHECK

   get/set certificate revocation list (CRL) check mode. CRL validation
   requires :py:const:`OPT_X_TLS_CRLFILE`.

   :py:const:`OPT_X_TLS_CRL_NONE`
      Don't perform CRL checks

   :py:const:`OPT_X_TLS_CRL_PEER`
      Perform CRL check for peer's end entity cert.

   :py:const:`OPT_X_TLS_CRL_ALL`
      Perform CRL checks for the whole cert chain

.. py:data:: OPT_X_TLS_CRLFILE

   get/set path to CRL file

.. py:data:: OPT_X_TLS_CRL_ALL

   value for :py:const:`OPT_X_TLS_CRLCHECK`

.. py:data:: OPT_X_TLS_CRL_NONE

   value for :py:const:`OPT_X_TLS_CRLCHECK`

.. py:data:: OPT_X_TLS_CRL_PEER

   value for :py:const:`OPT_X_TLS_CRLCHECK`


.. py:data:: OPT_X_TLS_REQUIRE_CERT

   get/set validation strategy for server cert.

   :py:const:`OPT_X_TLS_NEVER`
      Don't check server cert and host name

   :py:const:`OPT_X_TLS_ALLOW`
      Used internally by slapd server.

   :py:const:`OPT_X_TLS_DEMAND`
      Validate peer cert chain and host name

   :py:const:`OPT_X_TLS_HARD`
      Same as :py:const:`OPT_X_TLS_DEMAND`

.. py:data:: OPT_X_TLS_REQUIRE_SAN

   get/set how OpenLDAP validates subject alternative name extension,
   available in OpenLDAP 2.4.52 and newer.

   :py:const:`OPT_X_TLS_NEVER`
      Don't check SAN

   :py:const:`OPT_X_TLS_ALLOW`
      Check SAN first, always fall back to subject common name (default)

   :py:const:`OPT_X_TLS_TRY`
      Check SAN first, only fall back to subject common name, when no SAN
      extension is present (:rfc:`6125` conform validation)

   :py:const:`OPT_X_TLS_DEMAND`
      Validate peer cert chain and host name

   :py:const:`OPT_X_TLS_HARD`
      Require SAN, don't fall back to subject common name

   .. versionadded:: 3.4.0

.. py:data:: OPT_X_TLS_ALLOW

   Value for :py:const:`OPT_X_TLS_REQUIRE_CERT`
   and :py:const:`OPT_X_TLS_REQUIRE_SAN`

.. py:data:: OPT_X_TLS_DEMAND

   Value for :py:const:`OPT_X_TLS_REQUIRE_CERT`
   and :py:const:`OPT_X_TLS_REQUIRE_SAN`

.. py:data:: OPT_X_TLS_HARD

   Value for :py:const:`OPT_X_TLS_REQUIRE_CERT`
   and :py:const:`OPT_X_TLS_REQUIRE_SAN`

.. py:data:: OPT_X_TLS_NEVER

   Value for :py:const:`OPT_X_TLS_REQUIRE_CERT`
   and :py:const:`OPT_X_TLS_REQUIRE_SAN`

.. py:data:: OPT_X_TLS_TRY

   Value for :py:const:`OPT_X_TLS_REQUIRE_CERT`

   .. deprecated:: 3.3.0
      This value is only used by slapd server internally. It will be removed
      in the future.


.. py:data:: OPT_X_TLS_CIPHER

   get cipher suite name from TLS session

.. py:data:: OPT_X_TLS_CIPHER_SUITE

   get/set allowed cipher suites

.. py:data:: OPT_X_TLS_CTX

   get address of internal memory address of TLS context (**DO NOT USE**)

.. py:data:: OPT_X_TLS_PEERCERT

   Get peer's certificate as binary ASN.1 data structure (DER)

   .. versionadded:: 3.4.1

   .. note::
      The option leaks memory with OpenLDAP < 2.5.8.

.. py:data:: OPT_X_TLS_PROTOCOL_MIN

   get/set minimum protocol version (wire protocol version as int)

.. py:data:: OPT_X_TLS_PROTOCOL_MAX

   get/set maximum protocol version (wire protocol version as int),
   available in OpenLDAP 2.5 and newer.

   .. versionadded:: 3.4.1

.. py:data:: OPT_X_TLS_PROTOCOL_SSL3

   Value for :py:const:`OPT_X_TLS_PROTOCOL_MIN` and
   :py:const:`OPT_X_TLS_PROTOCOL_MAX`, represents SSL 3

   .. versionadded:: 3.4.1

.. py:data:: OPT_X_TLS_PROTOCOL_TLS1_0

   Value for :py:const:`OPT_X_TLS_PROTOCOL_MIN` and
   :py:const:`OPT_X_TLS_PROTOCOL_MAX`, represents TLS 1.0

   .. versionadded:: 3.4.1

.. py:data:: OPT_X_TLS_PROTOCOL_TLS1_1

   Value for :py:const:`OPT_X_TLS_PROTOCOL_MIN` and
   :py:const:`OPT_X_TLS_PROTOCOL_MAX`, represents TLS 1.1

   .. versionadded:: 3.4.1

.. py:data:: OPT_X_TLS_PROTOCOL_TLS1_2

   Value for :py:const:`OPT_X_TLS_PROTOCOL_MIN` and
   :py:const:`OPT_X_TLS_PROTOCOL_MAX`, represents TLS 1.2

   .. versionadded:: 3.4.1

.. py:data:: OPT_X_TLS_PROTOCOL_TLS1_3

   Value for :py:const:`OPT_X_TLS_PROTOCOL_MIN` and
   :py:const:`OPT_X_TLS_PROTOCOL_MAX`, represents TLS 1.3

   .. versionadded:: 3.4.1

.. py:data:: OPT_X_TLS_VERSION

   Get negotiated TLS protocol version as string

.. py:data:: OPT_X_TLS_RANDOM_FILE

   get/set path to /dev/urandom (**DO NOT USE**)

.. py:data:: OPT_X_TLS

   .. deprecated:: 3.3.0
      The option is deprecated in OpenLDAP and should no longer be used. It
      will be removed in the future.

.. note::

   OpenLDAP supports several TLS/SSL libraries. OpenSSL is the most common
   backend. Some options may not be available when libldap uses NSS, GnuTLS,
   or Apple's Secure Transport backend.

.. _ldap-keepalive-options:

Keepalive options
:::::::::::::::::

.. py:data:: OPT_X_KEEPALIVE_IDLE

.. py:data:: OPT_X_KEEPALIVE_PROBES

.. py:data:: OPT_X_KEEPALIVE_INTERVAL

.. _ldap-dn-flags:

DN format flags
----------------

This constants are used for DN-parsing functions found in
sub-module :py:mod:`ldap.dn`.

.. seealso::
   `ldap_str2dn(3) <https://www.openldap.org/software/man.cgi?query=ldap_str2dn&sektion=3>`_

.. py:data:: DN_FORMAT_LDAP

.. py:data:: DN_FORMAT_LDAPV3

.. py:data:: DN_FORMAT_LDAPV2

.. py:data:: DN_FORMAT_DCE

.. py:data:: DN_FORMAT_UFN

.. py:data:: DN_FORMAT_AD_CANONICAL

.. py:data:: DN_FORMAT_MASK

.. py:data:: DN_PRETTY

.. py:data:: DN_SKIP

.. py:data:: DN_P_NOLEADTRAILSPACES

.. py:data:: DN_P_NOSPACEAFTERRDN

.. py:data:: DN_PEDANTIC



.. _ldap-exceptions:

Exceptions
==========

The module defines the following exceptions:

.. py:exception:: LDAPError

   This is the base class of all exceptions raised by the module :py:mod:`ldap`.
   Unlike the C interface, errors are not returned as result codes, but
   are instead turned into exceptions, raised as soon an the error condition
   is detected.

   The exceptions are accompanied by a dictionary with additional information.
   All fields are optional and more fields may be added in the future.
   Currently, ``python-ldap`` may set the following fields:

   * ``'result'``: a numeric code of the error class.
   * ``'desc'``: string giving a description of the error class, as provided
     by calling OpenLDAP's ``ldap_err2string`` on the ``result``.
   * ``'info'``: string containing more information that the server may
     have sent. The value is server-specific: for example, the OpenLDAP server
     may send different info messages than Active Directory or 389-DS.
   * ``'matched'``: truncated form of the name provided or alias.
     dereferenced for the lowest entry (object or alias) that was matched.
   * ``'msgid'``: ID of the matching asynchronous request.
     This can be used in asynchronous code where :py:meth:`result()` raises the
     result of an operation as an exception. For example, this is the case for
     :py:meth:`~LDAPObject.compare()`, always raises the boolean result as an
     exception (:py:exc:`COMPARE_TRUE` or :py:exc:`COMPARE_FALSE`).
   * ``'ctrls'``: list of :py:class:`ldap.controls.LDAPControl` instances
     attached to the error.
   * ``'errno'``: the C ``errno``, usually set by system calls or ``libc``
     rather than the LDAP libraries.

.. py:exception:: ADMINLIMIT_EXCEEDED

.. py:exception:: AFFECTS_MULTIPLE_DSAS

.. py:exception:: ALIAS_DEREF_PROBLEM

   A problem was encountered when dereferencing an alias.
   (Sets the :py:const:`matched` field.)

.. py:exception:: ALIAS_PROBLEM

   An alias in the directory points to a nonexistent entry.
   (Sets the :py:const:`matched` field.)

.. py:exception:: ALREADY_EXISTS

   The entry already exists. E.g. the *dn* specified with :py:meth:`add()`
   already exists in the DIT.

.. py:exception:: AUTH_UNKNOWN

   The authentication method specified to :py:meth:`bind()` is not known.

.. py:exception:: BUSY

   The DSA is busy.

.. py:exception:: CLIENT_LOOP

.. py:exception:: COMPARE_FALSE

   A compare operation returned false.
   (This exception should only be seen asynchronous operations, because
   :py:meth:`~LDAPObject.compare_s()` returns a boolean result.)

.. py:exception:: COMPARE_TRUE

   A compare operation returned true.
   (This exception should only be seen asynchronous operations, because
   :py:meth:`~LDAPObject.compare_s()` returns a boolean result.)

.. py:exception:: CONFIDENTIALITY_REQUIRED

   Indicates that the session is not protected by a protocol such
   as Transport Layer Security (TLS), which provides session
   confidentiality.

.. py:exception:: CONNECT_ERROR

.. py:exception:: CONSTRAINT_VIOLATION

   An attribute value specified or an operation started violates some
   server-side constraint
   (e.g., a postalAddress has too many lines or a line that is too long
   or a password is expired).

.. py:exception:: CONTROL_NOT_FOUND

.. py:exception:: DECODING_ERROR

   An error was encountered decoding a result from the LDAP server.

.. py:exception:: ENCODING_ERROR

   An error was encountered encoding parameters to send to the LDAP server.

.. py:exception:: FILTER_ERROR

   An invalid filter was supplied to :py:meth:`search()`
   (e.g. unbalanced parentheses).

.. py:exception:: INAPPROPRIATE_AUTH

   Inappropriate authentication was specified (e.g. :py:const:`AUTH_SIMPLE`
   was specified and the entry does not have a userPassword attribute).

.. py:exception:: INAPPROPRIATE_MATCHING

   Filter type not supported for the specified attribute.

.. py:exception:: INSUFFICIENT_ACCESS

   The user has insufficient access to perform the operation.

.. py:exception:: INVALID_CREDENTIALS

   Invalid credentials were presented during :py:meth:`bind()` or
   :py:meth:`simple_bind()`.
   (e.g., the wrong password).

.. py:exception:: INVALID_DN_SYNTAX

   A syntactically invalid DN was specified. (Sets the :py:const:`matched` field.)

.. py:exception:: INVALID_SYNTAX

   An attribute value specified by the client did not comply to the
   syntax defined in the server-side schema.

.. py:exception:: IS_LEAF

   The object specified is a leaf of the directory tree.
   Sets the :py:const:`matched` field of the exception dictionary value.

.. py:exception:: LOCAL_ERROR

   Some local error occurred. This is usually due to failed memory allocation.

.. py:exception:: LOOP_DETECT

   A loop was detected.

.. py:exception:: MORE_RESULTS_TO_RETURN

.. py:exception:: NAMING_VIOLATION

   A naming violation occurred. This is raised e.g. if the LDAP server
   has constraints about the tree naming.

.. py:exception:: NO_OBJECT_CLASS_MODS

   Modifying the objectClass attribute as requested is not allowed
   (e.g. modifying structural object class of existing entry).

.. py:exception:: NOT_ALLOWED_ON_NONLEAF

   The operation is not allowed on a non-leaf object.

.. py:exception:: NOT_ALLOWED_ON_RDN

   The operation is not allowed on an RDN.

.. py:exception:: NOT_SUPPORTED

.. py:exception:: NO_MEMORY

.. py:exception:: NO_RESULTS_RETURNED

.. py:exception:: NO_SUCH_ATTRIBUTE

   The attribute type specified does not exist in the entry.

.. py:exception:: NO_SUCH_OBJECT

   The specified object does not exist in the directory.
   Sets the :py:const:`matched` field of the exception dictionary value.

.. py:exception:: OBJECT_CLASS_VIOLATION

   An object class violation occurred when the LDAP server checked
   the data sent by the client against the server-side schema
   (e.g. a "must" attribute was missing in the entry data).

.. py:exception:: OPERATIONS_ERROR

   An operations error occurred.

.. py:exception:: OTHER

   An unclassified error occurred.

.. py:exception:: PARAM_ERROR

   An ldap routine was called with a bad parameter.

.. py:exception:: PARTIAL_RESULTS

   Partial results only returned. This exception is raised if
   a referral is received when using LDAPv2.
   (This exception should never be seen with LDAPv3.)

.. py:exception:: PROTOCOL_ERROR

   A violation of the LDAP protocol was detected.

.. py:exception:: RESULTS_TOO_LARGE

   The result does not fit into a UDP packet. This happens only when using
   UDP-based CLDAP (connection-less LDAP) which is not supported anyway.

.. py:exception:: SASL_BIND_IN_PROGRESS

.. py:exception:: SERVER_DOWN

   The  LDAP  library  can't  contact the LDAP server.

.. py:exception:: SIZELIMIT_EXCEEDED

   An LDAP size limit was exceeded.
   This could be due to a ``sizelimit`` configuration on the LDAP server.

.. py:exception:: STRONG_AUTH_NOT_SUPPORTED

   The LDAP server does not support strong authentication.

.. py:exception:: STRONG_AUTH_REQUIRED

   Strong authentication is required  for the operation.

.. py:exception:: TIMELIMIT_EXCEEDED

   An LDAP time limit was exceeded.

.. py:exception:: TIMEOUT

   A timelimit was exceeded while waiting for a result from the server.

.. py:exception:: TYPE_OR_VALUE_EXISTS

   An  attribute  type or attribute value specified already
   exists in the entry.

.. py:exception:: UNAVAILABLE

   The DSA is unavailable.

.. py:exception:: UNAVAILABLE_CRITICAL_EXTENSION

   Indicates that the LDAP server was unable to satisfy a request
   because one or more critical extensions were not available. Either
   the server does not support the control or the control is not appropriate
   for the operation type.

.. py:exception:: UNDEFINED_TYPE

   An attribute type used is not defined in the server-side schema.

.. py:exception:: UNWILLING_TO_PERFORM

   The  DSA is  unwilling to perform the operation.

.. py:exception:: USER_CANCELLED

   The operation was cancelled via the :py:meth:`abandon()` method.

The above exceptions are raised when a result code from an underlying API
call does not indicate success.


.. _ldap-warnings:

Warnings
========

.. py:class:: LDAPBytesWarning

    This warning is deprecated. python-ldap no longer raises it.

    It used to be raised under Python 2 when bytes/text mismatch in non-strict
    bytes mode. See :ref:`bytes_mode` for details.

    .. versionadded:: 3.0.0

    .. versionchanged:: 3.4.0

      Deprecated.

.. _ldap-objects:

LDAPObject classes
==================

.. py:class:: ldap.ldapobject.LDAPObject

   Instances of :py:class:`LDAPObject` are returned by :py:func:`initialize()`.
   The connection is automatically unbound
   and closed when the LDAP object is deleted.

   :py:class:`LDAPObject` is an alias of
   :py:class:`~ldap.ldapobject.SimpleLDAPObject`, the default connection class.
   If you wish to use a different class, instantiate it directly instead of
   calling :func:`initialize()`.

   (It is also possible, but not recommended, to change the default by setting
   ``ldap.ldapobject.LDAPObject`` to a different class.)

.. autoclass:: ldap.ldapobject.SimpleLDAPObject

.. autoclass:: ldap.ldapobject.ReconnectLDAPObject


.. _ldap-controls:

Arguments for LDAPv3 controls
-----------------------------

The :py:mod:`ldap.controls` module can be used for constructing and
decoding LDAPv3 controls. These arguments are available in the methods
with names ending in :py:const:`_ext` or :py:const:`_ext_s`:

*serverctrls*
  is a list of :py:class:`ldap.controls.LDAPControl` instances sent to the server along
  with the LDAP request (see module :py:mod:`ldap.controls`). These are
  controls which alter the behaviour of the server when processing the
  request if the control is supported by the server. The effect of controls
  might differ depending on the type of LDAP request or controls might not
  be applicable with certain LDAP requests at all.

*clientctrls*
  is a list of :py:class:`ldap.controls.LDAPControl` instances passed to the
  client API and alter the behaviour of the client when processing the
  request.


.. _sending-ldap-requests:

Sending LDAP requests
---------------------

Most methods on LDAP objects initiate an asynchronous request to the
LDAP server and return a message id that can be used later to retrieve
the result with :py:meth:`result()`.

Methods with names ending in :py:const:`_s` are the synchronous form
and wait for and return with the server's result, or with
:py:const:`None` if no data is expected.


:class:`LDAPObject` instances have the following methods:

.. py:method:: LDAPObject.abandon(msgid) -> None

.. py:method:: LDAPObject.abandon_ext(msgid [, serverctrls=None [, clientctrls=None]]) -> None

   Abandons an LDAP operation in progress without waiting for a LDAP response.
   The *msgid* argument should be the message ID of an outstanding LDAP
   operation as returned by the asynchronous methods :py:meth:`search()`, :py:meth:`modify()`, etc.
   The caller can expect that the result of an abandoned operation will not be
   returned from a future call to :py:meth:`result()`.

   *serverctrls* and *clientctrls* like described in section :ref:`ldap-controls`.


.. py:method:: LDAPObject.add(dn, modlist) -> int

.. py:method:: LDAPObject.add_s(dn, modlist) -> None

.. py:method:: LDAPObject.add_ext(dn, modlist [, serverctrls=None [, clientctrls=None]]) -> int

.. py:method:: LDAPObject.add_ext_s(dn, modlist [, serverctrls=None [, clientctrls=None]]) -> tuple

   Performs an LDAP add operation. The *dn* argument is the distinguished
   name (DN) of the entry to add, and *modlist* is a list of attributes to be
   added. The modlist is similar the one passed to :py:meth:`modify()`, except that the
   operation integer is omitted from the tuples in modlist. You might want to
   look into sub-module \refmodule{ldap.modlist} for generating the modlist.

   The asynchronous methods :py:meth:`add()` and :py:meth:`add_ext()`
   return the message ID of the initiated request.

   *serverctrls* and *clientctrls* like described in section :ref:`ldap-controls`.

   The *dn* argument, and mod_type (second item) of *modlist* are text strings;
   see :ref:`bytes_mode`.


.. py:method:: LDAPObject.bind(who, cred, method) -> int

.. py:method:: LDAPObject.bind_s(who, cred, method) -> None

.. py:method:: LDAPObject.cancel( cancelid, [, serverctrls=None [, clientctrls=None]]) -> None

   Send cancels extended operation for an LDAP operation specified by *cancelid*.
   The *cancelid* should be the message id of an outstanding LDAP operation as returned
   by the asynchronous methods search(), modify() etc.  The caller
   can expect that the result of an abandoned operation will not be
   returned from a future call to :py:meth:`result()`.
   In opposite to :py:meth:`abandon()` this extended operation gets an result from
   the server and thus should be preferred if the server supports it.

   *serverctrls* and *clientctrls* like described in section :ref:`ldap-controls`.

   :rfc:`3909` - Lightweight Directory Access Protocol (LDAP): Cancel Operation


.. py:method:: LDAPObject.compare(dn, attr, value) -> int

.. py:method:: LDAPObject.compare_s(dn, attr, value) -> bool

.. py:method:: LDAPObject.compare_ext(dn, attr, value [, serverctrls=None [, clientctrls=None]]) -> int

.. py:method:: LDAPObject.compare_ext_s(dn, attr, value [, serverctrls=None [, clientctrls=None]]) -> bool

   Perform an LDAP comparison between the attribute named *attr* of entry *dn*,
   and the value *value*. The synchronous forms returns ``True`` or ``False``.
   The asynchronous forms returns the message ID of the initiated request, and
   the result of the asynchronous compare can be obtained using
   :py:meth:`result()`. The operation can fail with an exception, e.g.
   :py:exc:`ldap.NO_SUCH_OBJECT` when *dn* does not exist or
   :py:exc:`ldap.UNDEFINED_TYPE` for an invalid attribute.

   Note that the asynchronous technique yields the answer
   by raising the exception objects :py:exc:`ldap.COMPARE_TRUE` or
   :py:exc:`ldap.COMPARE_FALSE`.

   *serverctrls* and *clientctrls* like described in section :ref:`ldap-controls`.

   The *dn* and *attr* arguments are text strings; see :ref:`bytes_mode`.


.. py:method:: LDAPObject.delete(dn) -> int

.. py:method::  LDAPObject.delete_s(dn) -> None

.. py:method:: LDAPObject.delete_ext(dn [, serverctrls=None [, clientctrls=None]]) -> int

.. py:method:: LDAPObject.delete_ext_s(dn [, serverctrls=None [, clientctrls=None]]) -> tuple

   Performs an LDAP delete operation on *dn*. The asynchronous form
   returns the message id of the initiated request, and the result can be obtained
   from a subsequent call to :py:meth:`result()`.

   *serverctrls* and *clientctrls* like described in section :ref:`ldap-controls`.

   The *dn* argument is text string; see :ref:`bytes_mode`.


.. py:method:: LDAPObject.extop(extreq[,serverctrls=None[,clientctrls=None]]]) -> int

.. py:method:: LDAPObject.extop_s(extreq[,serverctrls=None[,clientctrls=None[,extop_resp_class=None]]]]) -> (respoid,respvalue)

   Performs an LDAP extended operation. The asynchronous
   form returns the message id of the initiated request, and the
   result can be obtained from a subsequent call to :py:meth:`extop_result()`.

   The *extreq* is an instance of class :py:class:`ldap.extop.ExtendedRequest`
   containing the parameters for the extended operation request.

   *serverctrls* and *clientctrls* like described in section :ref:`ldap-controls`.

   If argument *extop_resp_class* is set to a sub-class of
   :py:class:`ldap.extop.ExtendedResponse` this class is used to return an
   object of this class instead of a raw BER value in respvalue.

.. py:method:: LDAPObject.extop_result(self,msgid=ldap.RES_ANY,all=1,timeout=None) -> (respoid,respvalue)

   Wrapper method around :py:meth:`result4()` just for retrieving
   the result of an extended operation sent before.


.. py:method:: LDAPObject.modify(dn, modlist) -> int

.. py:method:: LDAPObject.modify_s(dn, modlist) -> None

.. py:method:: LDAPObject.modify_ext(dn, modlist [, serverctrls=None [, clientctrls=None]]) -> int

.. py:method:: LDAPObject.modify_ext_s(dn, modlist [, serverctrls=None [, clientctrls=None]]) -> tuple

   Performs an LDAP modify operation on an entry's attributes.
   The *dn* argument is the distinguished name (DN) of the entry to modify,
   and *modlist* is a list of modifications to make to that entry.

   Each element in the list *modlist* should be a tuple of the form
   *(mod_op,mod_type,mod_vals)*,
   where *mod_op* indicates the operation (one of :py:const:`ldap.MOD_ADD`,
   :py:const:`ldap.MOD_DELETE`, or :py:const:`ldap.MOD_REPLACE`),
   *mod_type* is a string indicating the attribute type name, and
   *mod_vals* is either a string value or a list of string values to add,
   delete or replace respectively.  For the delete operation, *mod_vals*
   may be :py:const:`None` indicating that all attributes are to be deleted.

   *serverctrls* and *clientctrls* like described in section :ref:`ldap-controls`.

   The asynchronous methods :py:meth:`modify()` and :py:meth:`modify_ext()`
   return the message ID of the initiated request.

   You might want to look into sub-module :py:mod:`ldap.modlist` for
   generating *modlist*.

   The *dn* argument, and mod_type (second item) of *modlist* are text strings;
   see :ref:`bytes_mode`.


.. py:method:: LDAPObject.modrdn(dn, newrdn [, delold=1]) -> int


.. py:method::  LDAPObject.modrdn_s(dn, newrdn [, delold=1]) -> None

   Perform a ``modify RDN`` operation, (i.e. a renaming operation).
   These routines take *dn* (the DN of the entry whose RDN is to be changed,
   and *newrdn*, the new RDN to give to the entry. The optional parameter
   *delold* is used to specify whether the old RDN should be kept as an
   attribute of the entry or not.
   The asynchronous version returns the initiated message id.

   This operation is emulated by :py:meth:`rename()` and :py:meth:`rename_s()` methods
   since the modrdn2* routines in the C library are deprecated.

   The *dn* and *newrdn* arguments are text strings; see :ref:`bytes_mode`.


.. py:method:: LDAPObject.passwd(user, oldpw, newpw [, serverctrls=None [, clientctrls=None]]) -> int

.. py:method:: LDAPObject.passwd_s(user, oldpw, newpw [, serverctrls=None [, clientctrls=None] [, extract_newpw=False]]]) -> (respoid, respvalue)

   Perform a ``LDAP Password Modify Extended Operation`` operation
   on the entry specified by *user*.
   The old password in *oldpw* is replaced with the new
   password in *newpw* by a LDAP server supporting this operation.

   If *oldpw* is not :py:const:`None` it has to match the old password
   of the specified *user* which is sometimes used when a user changes
   his own password.

   *respoid* is always :py:const:`None`. *respvalue* is also
   :py:const:`None` unless *newpw* was :py:const:`None`. This requests that
   the server generate a new random password. If *extract_newpw* is
   :py:const:`True`, this password is a bytes object available through
   ``respvalue.genPasswd``, otherwise *respvalue* is the raw ASN.1 response
   (this is deprecated and only for backwards compatibility).

   *serverctrls* and *clientctrls* like described in section :ref:`ldap-controls`.

   The asynchronous version returns the initiated message id.

   The *user*, *oldpw* and *newpw* arguments are text strings; see :ref:`bytes_mode`.

   .. seealso::

      :rfc:`3062` - LDAP Password Modify Extended Operation
      :py:mod:`ldap.extop.passwd`



.. py:method:: LDAPObject.rename(dn, newrdn [, newsuperior=None [, delold=1 [, serverctrls=None [, clientctrls=None]]]]) -> int

.. py:method:: LDAPObject.rename_s(dn, newrdn [, newsuperior=None [, delold=1 [, serverctrls=None [, clientctrls=None]]]]) -> None

   Perform a ``Rename`` operation, (i.e. a renaming operation).
   These routines take *dn* (the DN of the entry whose RDN is to be changed,
   and *newrdn*, the new RDN to give to the entry.
   The optional parameter *newsuperior* is used to specify
   a new parent DN for moving an entry in the tree
   (not all LDAP servers support this).
   The optional parameter *delold* is used to specify
   whether the old RDN should be kept as an attribute of the entry or not.

   *serverctrls* and *clientctrls* like described in section :ref:`ldap-controls`.

   The *dn* and *newdn* arguments are text strings; see :ref:`bytes_mode`.


.. py:method:: LDAPObject.result([msgid=RES_ANY [, all=1 [, timeout=None]]]) -> 2-tuple

   This method is used to wait for and return the result of an operation
   previously initiated by one of the LDAP *asynchronous* operations
   (e.g. :py:meth:`search()`, :py:meth:`modify()`, etc.)

   The *msgid* parameter is the integer identifier returned by that method.
   The identifier is guaranteed to be unique across an LDAP session,
   and tells the :py:meth:`result()` method to request the result of that
   specific operation.

   If a result is desired from any one of the in-progress operations,
   *msgid* should be specified as the constant :py:const:`RES_ANY`
   and the method :py:meth:`result2()` should be used instead.

   The *all* parameter only has meaning for :py:meth:`search()` responses
   and is used to select whether a single entry of the search
   response should be returned, or to wait for all the results
   of the search before returning.

   A search response is made up of zero or more search entries
   followed by a search result. If *all* is 0, search entries will
   be returned one at a time as they come in, via separate calls
   to :py:meth:`result()`. If all is 1, the search response will be returned
   in its entirety, i.e. after all entries and the final search
   result have been received.

   For *all* set to 0, result tuples
   trickle in (with the same message id), and with the result types
   :py:const:`RES_SEARCH_ENTRY` and :py:const:`RES_SEARCH_REFERENCE`,
   until the final result which has a result type of :py:const:`RES_SEARCH_RESULT`
   and a (usually) empty data field.  When all is set to 1, only one result is returned,
   with a result type of RES_SEARCH_RESULT, and all the result tuples
   listed in the data field.

   The *timeout* parameter is a limit on the number of seconds that the
   method will wait for a response from the server.
   If *timeout* is negative (which is the default),
   the method will wait indefinitely for a response.
   The timeout can be expressed as a floating-point value, and
   a value of :py:const:`0` effects a poll.
   If a timeout does occur, a :py:exc:`ldap.TIMEOUT` exception is raised,
   unless polling, in which case ``(None, None)`` is returned.

   The :py:meth:`result()` method returns a tuple of the form
   ``(result-type, result-data)``.
   The first element, ``result-type`` is a string, being one of
   these module constants:
   :py:const:`RES_BIND`, :py:const:`RES_SEARCH_ENTRY`,
   :py:const:`RES_SEARCH_REFERENCE`, :py:const:`RES_SEARCH_RESULT`,
   :py:const:`RES_MODIFY`, :py:const:`RES_ADD`, :py:const:`RES_DELETE`,
   :py:const:`RES_MODRDN`, or :py:const:`RES_COMPARE`.

   If *all* is :py:const:`0`, one response at a time is returned on
   each call to :py:meth:`result()`, with termination indicated by
   ``result-data`` being an empty list.

   See :py:meth:`search()` for a description of the search result's
   ``result-data``, otherwise the ``result-data`` is normally meaningless.



.. py:method:: LDAPObject.result2([msgid=RES_ANY [, all=1 [, timeout=None]]]) -> 3-tuple

   This method behaves almost exactly like :py:meth:`result()`. But
   it returns a 3-tuple also containing the message id of the
   outstanding LDAP operation a particular result message belongs
   to. This is especially handy if one needs to dispatch results
   obtained with ``msgid=``:py:const:`RES_ANY` to several consumer
   threads which invoked a particular LDAP operation.


.. py:method:: LDAPObject.result3([msgid=RES_ANY [, all=1 [, timeout=None]]]) -> 4-tuple

   This method behaves almost exactly like :py:meth:`result2()`. But it
   returns an extra item in the tuple, the decoded server controls.

.. py:method:: LDAPObject.result4([msgid=RES_ANY [, all=1 [, timeout=None [, add_ctrls=0 [, add_intermediates=0 [, add_extop=0 [, resp_ctrl_classes=None]]]]]]]) -> 6-tuple

   This method behaves almost exactly like :py:meth:`result3()`. But it
   returns an extra items in the tuple, the decoded results of an extended response.

   The additional arguments are:

   *add_ctrls* (integer flag) specifies whether response controls are returned.

   add_intermediates (integer flag) specifies whether response controls of
   intermediate search results are returned.

   *add_extop* (integer flag) specifies whether the response of an
   extended operation is returned. If using extended operations you should
   consider using the method :py:meth:`extop_result()` or
   :py:meth:`extop_s()` instead.

   *resp_ctrl_classes* is a dictionary mapping the OID of a response controls to a
   :py:class:`ldap.controls.ResponseControl` class of response controls known by the
   application. So the response control value will be automatically decoded.
   If :py:const:`None` the global dictionary :py:data:`ldap.controls.KNOWN_RESPONSE_CONTROLS`
   is used instead.

.. py:method:: LDAPObject.sasl_interactive_bind_s(who, auth[, serverctrls=None [, clientctrls=None [, sasl_flags=ldap.SASL_QUIET]]]) -> None

   This call is used to bind to the directory with a SASL bind request.

   *auth* is an :py:class:`ldap.sasl.sasl()` instance.

   *serverctrls* and *clientctrls* like described in section :ref:`ldap-controls`.


.. py:method:: LDAPObject.sasl_non_interactive_bind_s(sasl_mech[, serverctrls=None [, clientctrls=None [, sasl_flags=ldap.SASL_QUIET [, authz_id='']]]]) -> None

   This call is used to bind to the directory with a SASL bind request with
   non-interactive SASL mechanism defined with argument *sasl_mech* and
   internally calls :py:meth:`sasl_interactive_bind_s()`.

   *serverctrls* and *clientctrls* like described in section :ref:`ldap-controls`.


.. py:method:: LDAPObject.sasl_external_bind_s([serverctrls=None [, clientctrls=None [, sasl_flags=ldap.SASL_QUIET [, authz_id='']]]]) -> None

   This call is used to bind to the directory with a SASL bind request with
   mechanism EXTERNAL and internally calls :py:meth:`sasl_non_interactive_bind_s()`.

   *serverctrls* and *clientctrls* like described in section :ref:`ldap-controls`.


.. py:method:: LDAPObject.sasl_gssapi_bind_s([serverctrls=None [, clientctrls=None [, sasl_flags=ldap.SASL_QUIET [, authz_id='']]]]) -> None

   This call is used to bind to the directory with a SASL bind request with
   mechanism GSSAPI and internally calls :py:meth:`sasl_non_interactive_bind_s()`.

   *serverctrls* and *clientctrls* like described in section :ref:`ldap-controls`.


.. py:method:: LDAPObject.simple_bind([who=None [, cred=None [, serverctrls=None [, clientctrls=None]]]]) -> int

.. py:method:: LDAPObject.simple_bind_s([who=None [, cred=None [, serverctrls=None [, clientctrls=None]]]]) -> None

   After an LDAP object is created, and before any other operations can be
   attempted over the connection, a bind operation must be performed.

   This method attempts to bind with the LDAP server using
   either simple authentication, or Kerberos (if available).
   The first and most general method, :py:meth:`bind()`,
   takes a third parameter, *method* which can currently solely
   be :py:const:`AUTH_SIMPLE`.

   *serverctrls* and *clientctrls* like described in section :ref:`ldap-controls`.

   The *who* and *cred* arguments are text strings; see :ref:`bytes_mode`.

   .. versionchanged:: 3.0

      :meth:`~LDAPObject.simple_bind` and :meth:`~LDAPObject.simple_bind_s`
      now accept ``None`` for *who* and *cred*, too.

.. py:method:: LDAPObject.search(base, scope [,filterstr='(objectClass=*)' [, attrlist=None [, attrsonly=0]]]) ->int

.. py:method:: LDAPObject.search_s(base, scope [,filterstr='(objectClass=*)' [, attrlist=None [, attrsonly=0]]]) ->list|None

.. py:method:: LDAPObject.search_st(base, scope [,filterstr='(objectClass=*)' [, attrlist=None [, attrsonly=0 [, timeout=-1]]]]) -> list|None

.. py:method:: LDAPObject.search_ext(base, scope [,filterstr='(objectClass=*)' [, attrlist=None [, attrsonly=0 [, serverctrls=None [, clientctrls=None [, timeout=-1 [, sizelimit=0]]]]]]]) -> int

.. py:method:: LDAPObject.search_ext_s(base, scope [,filterstr='(objectClass=*)' [, attrlist=None [, attrsonly=0 [, serverctrls=None [, clientctrls=None [, timeout=-1 [, sizelimit=0]]]]]]]) -> list|None

   Perform an LDAP search operation, with *base* as the DN of the entry
   at which to start the search, *scope* being one of
   :py:const:`SCOPE_BASE` (to search the object itself),
   :py:const:`SCOPE_ONELEVEL` (to search the object's immediate children), or
   :py:const:`SCOPE_SUBTREE` (to search the object and all its descendants).

   The *filterstr* argument is a string representation of the filter to apply in
   the search.

   .. seealso::

      :rfc:`4515` - Lightweight Directory Access Protocol (LDAP): String Representation of Search Filters.


   Each result tuple is of the form ``(dn, attrs)``,
   where *dn* is a string containing the DN (distinguished name) of the
   entry, and *attrs* is a dictionary containing the attributes associated
   with the entry. The keys of *attrs* are strings, and the associated
   values are lists of strings.

   The DN in *dn* is automatically extracted using the underlying libldap
   function :c:func:`ldap_get_dn()`, which may raise an exception if the
   DN is malformed.

   If *attrsonly* is non-zero, the values of *attrs* will be meaningless
   (they are not transmitted in the result).

   The retrieved attributes can be limited with the *attrlist* parameter.
   If *attrlist* is :py:const:`None`, all the attributes of each entry are returned.

   *serverctrls* and *clientctrls* like described in section :ref:`ldap-controls`.

   The synchronous form with timeout, :py:meth:`search_st()` or :py:meth:`search_ext_s()`,
   will block for at most *timeout* seconds (or indefinitely if *timeout*
   is negative). A :py:exc:`ldap.TIMEOUT` exception is raised if no result is received
   within the specified time.

   The amount of search results retrieved can be limited with the
   *sizelimit* parameter when using :py:meth:`search_ext()`
   or :py:meth:`search_ext_s()` (client-side search limit). If non-zero
   not more than *sizelimit* results are returned by the server.

   The *base* and *filterstr* arguments, and *attrlist* contents,
   are text strings; see :ref:`bytes_mode`.

   .. versionchanged:: 3.0

      ``filterstr=None`` is equivalent to ``filterstr='(objectClass=*)'``.


.. py:method:: LDAPObject.start_tls_s() -> None

   Negotiate TLS with server. The ``version`` attribute must have been
   set to :py:const:`VERSION3` (which it is by default) before calling this method.
   If TLS could not be started an exception will be raised.

  .. seealso::

    :rfc:`2830` - Lightweight Directory Access Protocol (v3): Extension for Transport Layer Security


.. py:method:: LDAPObject.unbind() -> int

.. py:method:: LDAPObject.unbind_s() -> None

.. py:method:: LDAPObject.unbind_ext([, serverctrls=None [, clientctrls=None]]) -> int

.. py:method:: LDAPObject.unbind_ext_s([, serverctrls=None [, clientctrls=None]]) -> None

   This call is used to unbind from the directory, terminate the
   current association, and free resources. Once called, the connection to the
   LDAP server is closed and the LDAP object is marked invalid.
   Further invocation of methods on the object will yield exceptions.

   *serverctrls* and *clientctrls* like described in section :ref:`ldap-controls`.

   These methods are all synchronous in nature.


.. py:method:: LDAPObject.whoami_s() -> string

   This synchronous method implements the LDAP "Who Am I?"
   extended operation.

   It is useful for finding out to find out which identity
   is assumed by the LDAP server after a SASL bind.

   .. seealso::

      :rfc:`4532` - Lightweight Directory Access Protocol (LDAP) "Who am I?" Operation


Connection-specific LDAP options
--------------------------------

.. py:method:: LDAPObject.get_option(option) -> int|string

   This method returns the value of the LDAPObject option
   specified by *option*.


.. py:method:: LDAPObject.set_option(option, invalue) -> None

   This method sets the value of the LDAPObject option
   specified by *option* to *invalue*.


Object attributes
-----------------

If the underlying library provides enough information,
each LDAP object will also have the following attributes.
These attributes are mutable unless described as read-only.

.. py:attribute:: LDAPObject.deref -> int

   Controls whether aliases are automatically dereferenced.
   This must be one of :py:const:`DEREF_NEVER`, :py:const:`DEREF_SEARCHING`,
   :py:const:`DEREF_FINDING` or :py:const:`DEREF_ALWAYS`.
   This option is mapped to option constant :py:const:`OPT_DEREF`
   and used in the underlying OpenLDAP client lib.


.. py:attribute:: LDAPObject.network_timeout -> int

   Limit on waiting for a network response, in seconds.
   Defaults to :py:const:`NO_LIMIT`.
   This option is mapped to option constant :py:const:`OPT_NETWORK_TIMEOUT`
   and used in the underlying OpenLDAP client lib.

   .. versionchanged:: 3.0.0
      A timeout of ``-1`` or ``None`` resets timeout to infinity.

.. py:attribute:: LDAPObject.protocol_version -> int

   Version of LDAP in use (either :py:const:`VERSION2` for LDAPv2
   or :py:const:`VERSION3` for LDAPv3).
   This option is mapped to option constant :py:const:`OPT_PROTOCOL_VERSION`
   and used in the underlying OpenLDAP client lib.

   .. note::

      It is highly recommended to set the protocol version after establishing
      a LDAP connection with :py:func:`ldap.initialize()` and before submitting
      the first request.


.. py:attribute:: LDAPObject.sizelimit -> int

   Limit on size of message to receive from server.
   Defaults to :py:const:`NO_LIMIT`.
   This option is mapped to option constant :py:const:`OPT_SIZELIMIT`
   and used in the underlying OpenLDAP client lib. Its use is deprecated
   in favour of *sizelimit* parameter when using :py:meth:`search_ext()`.


.. py:attribute:: LDAPObject.timelimit -> int

   Limit on waiting for any response, in seconds.
   Defaults to :py:const:`NO_LIMIT`.
   This option is mapped to option constant :py:const:`OPT_TIMELIMIT`
   and used in the underlying OpenLDAP client lib. Its use is deprecated
   in favour of using :py:attr:`timeout`.


.. py:attribute:: LDAPObject.timeout -> int

   Limit on waiting for any response, in seconds.
   Defaults to :py:const:`NO_LIMIT`.
   This option is used in the wrapper module.


.. _ldap-example:

Example
=======

The following example demonstrates how to open a connection to an
LDAP server using the :py:mod:`ldap` module and invoke a synchronous
subtree search.

>>> import ldap
>>> l = ldap.initialize('ldap://localhost:1390')
>>> l.search_s('ou=Testing,dc=stroeder,dc=de',ldap.SCOPE_SUBTREE,'(cn=fred*)',['cn','mail'])
[('cn=Fred Feuerstein,ou=Testing,dc=stroeder,dc=de', {'cn': ['Fred Feuerstein']})]
>>> r = l.search_s('ou=Testing,dc=stroeder,dc=de',ldap.SCOPE_SUBTREE,'(objectClass=*)',['cn','mail'])
>>> for dn,entry in r:
>>>   print('Processing',repr(dn))
>>>   handle_ldap_entry(entry)