end0tknr's kipple - web写経開発

太宰府天満宮の狛犬って、妙にカワイイ

ldap3 for python による ldap 検索

次のようになると思います

#!/usr/local/bin/python
# -*- coding: utf-8 -*-

import sys
from ldap3 import *
#from ldap3 import Server, Connection, ALL, NTLM, ALL_ATTRIBUTES,
#                  ALL_OPERATIONAL_ATTRIBUTES, AUTO_BIND_NO_TLS, SUBTREE


def main():
    server = Server("ldap.ないしょ.co.jp", get_info=ALL)
    conn = Connection(server,
                      read_only=True,
                      auto_bind=True)
    # conn = Connection(server,
    #                   user='ないしょ',
    #                   password='ないしょ',
    #                   check_names=True,
    #                   read_only=True,
    #                   auto_bind=True)

    mail_addrs_file = sys.argv[1]

    in_f = open(mail_addrs_file, mode='r',encoding='utf-8')

    i = 0
    for line in in_f:
        i += 1
        print(i, file=sys.stderr)
        mail_addr = line.strip()

        if len(mail_addr) ==0:
            continue

        conn.search("ou=people,o=sexy-group",
                    "(mail=" + mail_addr + ")",
                    attributes = [ALL_ATTRIBUTES, ALL_OPERATIONAL_ATTRIBUTES],
                    # attributes=['cn', 'displayName', 'description'],
                    paged_size=1)

        if len(conn.entries) == 0:
            print(mail_addr)
            continue

        entry = conn.entries[0]

        disp_cols = [mail_addr]
        for atri_key in ["uid","cn","o","ou"]:
            if (atri_key in entry) ==True:
                disp_cols.append( str( entry[atri_key]) )
            else:
                disp_cols.append("")

        atri_key ="sexyIdCardDepartment"
        if (atri_key in entry) ==True:
            disp_cols.append( str( entry[atri_key][0]) )
        else:
            disp_cols.append("")


        print( "\t".join(disp_cols) )


    in_f.close()

        
if __name__ == '__main__':
    main()