from ldap3 import Server, Connection, ALL, ALL_ATTRIBUTES, ALL_OPERATIONAL_ATTRIBUTES
# from ldap3.core.exceptions import LDAPCursorError


def connect_ldap3():
    server = Server('localhost:10389', get_info=ALL, use_ssl=False)
    # conn = Connection(server, 'uid=admin,ou=system', 'gc01gapsC$', auto_bind='TLS_AFTER_BIND')  # 'uid=admin,ou=system'
    # status = conn.search('ou=cognos,dc=ibm,dc=com', '(objectclass=person)', 'SUBTREE')
    # print(conn.entries)
    conn = Connection(server, user='uid=Global1,ou=cognos,dc=ibm,dc=com', password='Cognos#11')
    if conn.bind():
        conn.search('ou=cognos,dc=ibm,dc=com', '(objectclass=person)', 'SUBTREE', attributes=[ALL_ATTRIBUTES, ALL_OPERATIONAL_ATTRIBUTES])
        format_string = '{:15} {:25} {:19} {:25} {}'
        for e in conn.entries:
            desc = ""
            email = ""
            if 'description' in e:
                desc = e.description
            if 'mail' in e:
                email = e.mail
            # print(e.entry_to_json())
            print(format_string.format(str(e.uid), str(e.givenName), str(e.createTimestamp)[:19], str(email), desc))
    else:
        print(conn.result)


if __name__ == '__main__':
    # connect_pyldap()
    connect_ldap3()

# from ldap3 import Server, Connection, AUTH_SIMPLE, STRATEGY_SYNC, ALL
# s = Server(HOST, port=389, get_info=ALL)
# c = Connection(s, authentication=AUTH_SIMPLE, user=user_dn, password=PASSWORD, check_names=True,
# lazy=False, client_strategy=STRATEGY_SYNC, raise_exceptions=True)
# c.open()
# c.bind()
