Skip to content

Instantly share code, notes, and snippets.

@yszou
Created December 9, 2013 11:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yszou/7870791 to your computer and use it in GitHub Desktop.
Save yszou/7870791 to your computer and use it in GitHub Desktop.
LDAP的一个查询交互
# -*- coding: utf-8 -*-
import sys
import ldap
ldap.set_option(ldap.OPT_REFERRALS, 0)
con = ldap.initialize('ldap://ldap.example.com:389')
con.simple_bind_s( 'xxx@sohu-inc.com', '***' )
base_dn = 'dc=sohu-inc,dc=com'
scope = ldap.SCOPE_SUBTREE
input = sys.argv[1]
filter = "(&(|(cn=*%(input)s*)(mail=*%(input)s*))(mail=*))" % {'input': input}
attrs = ['mail', 'givenName', 'sn', 'department', 'telephoneNumber', 'displayName']
result = []
for i in con.search_s(base_dn, scope, filter, None):
if i[0]:
d = {}
for k in i[1]:
d[k] = i[1][k][0]
if 'telephoneNumber' not in d:
d['telephoneNumber'] = '(无电话)'
if 'department' not in d:
d['department'] = '(无部门)'
if 'sn' not in d and 'givenName' not in d:
d['givenName'] = d.get('displayName', '')
if 'sn' not in d:
d['sn'] = ''
if 'givenName' not in d:
d['givenName'] = ''
result.append(d)
print '共找到结果 %s 条' % (len(result))
for d in result:
print '%(mail)s\t%(sn)s%(givenName)s\t%(telephoneNumber)s %(department)s' % d
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment