Nugget post: Setting ldap connection timeout for python

This blog post is similar to a previous one that dealt with PHP + LDAP. In this post we’ll explore how to use the python LDAP library and set timeouts. These settings are used to reduce the timeouts when connecting to an LDAP server. This will avoid your program from “hanging” due to lack of responsiveness from the LDAP server. This is done as follows:

import ldap

ld = ldap.initialize(‘ldap://2.3.4.5:389’)

# timeout relatively quickly if the server does not respond

self.ld.set_option(ldap.OPT_NETWORK_TIMEOUT,3.0)

self.ld.set_option(ldap.OPT_TIMEOUT,3.0)

#do not bother with referrals

self.ld.set_option(ldap.OPT_REFERRALS,0)

OPT_NETWORK_TIMEOUT, and OPT_TIMEOUT deal directly with timeouts, in this case they are set to 3 seconds. Also of note is the OPT_REFERRALS option, which is set to 0 to prevent the python ldap client from attempting to follow any LDAP referrals. Unless necessary, these should be disabled since the client will waste time checking the referrals for further results to an LDAP query.