Skip to content Skip to sidebar Skip to footer

Python And Ldap Via Ssl

I try to query an Active Directory Server with python which works fine. But now I don't want to send my credentials unencrypted on the wire, so I'd like to use LDAPs. Is there an

Solution 1:

i was doing some tests with a Samba4 DC and python ldap module and i've done this example:

#!/usr/bin/env python2# -*- coding: utf-8 -*-import ldap, ldapurl, subprocess, sys, shlex, os

GrupoLDAP = "Domain Users"#Grupo a recuperar
CACert = '/etc/cert/ca.cert.pem'#Certificado CA

ldap.set_option(ldap.OPT_X_TLS_CACERTFILE, CACert)
ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_HARD)

proto = 'ldaps'#Protocolo
server = 'domain.com'#Dirección del servidor (mismo nombre del Certificado)
port = 636#Puerto seguro para ldapstry:
    url = ldapurl.LDAPUrl(urlscheme=proto, hostport="%s:%s" % (server, str(port))).initializeUrl()
    ldap_obj = ldap.initialize(url)
    ldap_obj.simple_bind_s('user@domain.com','PassWord')

    base = 'OU=Users,DC=domain,DC=com'#Ruta y UO del grupo

    scope = ldap.SCOPE_SUBTREE

    query = '(&(objectClass=person)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))'

    res_attrs = ['sAMAccountName', 'cn']
    #res_attrs = ['*']
    res = ldap_obj.search_s(base, scope, query, res_attrs)
except ldap.LDAPError as Error:
    print"Ha ocurrido un error al conectar o realizar la query al servidor LDAP:\n\n%s" % Error
    sys.exit(1)

The certificate needs the FQDN in CN and be signed by the CA cert to avoid Certs error. Was working until I've added a second DC to same FQDN but if you only have one DC it should work. I don't know how it works on a Windows LDAP, but seems to be similar.

Greetings!!

Solution 2:

2 years ago, hm.... ok, may be too late.

however, try below codes. works for me for python/ldap/active directory/TLS.

import ldap
ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_ALLOW)
l = ldap.initialize("ldaps://ad.xxx.yyy:636")
l.set_option(ldap.OPT_REFERRALS, 0)
l.simple_bind_s("xxx\username", 'pw')
l.search_s('DC=AD,DC=XXX,DC=YYY', ldap.SCOPE_SUBTREE, '(samaccountname=username)', ['displayname'])

Post a Comment for "Python And Ldap Via Ssl"