[Py3] Update Demo to use print() (the function)

This commit is contained in:
Raphaël Barrois 2015-07-16 21:38:42 +02:00
parent 4a6f64f59e
commit 3091fe98ef
26 changed files with 209 additions and 185 deletions

View File

@ -1,3 +1,5 @@
from __future__ import print_function
import ldap,ldap.async import ldap,ldap.async
class DeleteLeafs(ldap.async.AsyncSearchHandler): class DeleteLeafs(ldap.async.AsyncSearchHandler):
@ -62,7 +64,7 @@ def DelTree(l,dn,scope=ldap.SCOPE_ONELEVEL):
non_leaf_entries = leafs_deleter.nonLeafEntries[:] non_leaf_entries = leafs_deleter.nonLeafEntries[:]
while non_leaf_entries: while non_leaf_entries:
dn = non_leaf_entries.pop() dn = non_leaf_entries.pop()
print deleted_entries,len(non_leaf_entries),dn print(deleted_entries,len(non_leaf_entries),dn)
leafs_deleter.startSearch(dn,ldap.SCOPE_SUBTREE) leafs_deleter.startSearch(dn,ldap.SCOPE_SUBTREE)
leafs_deleter.processResults() leafs_deleter.processResults()
deleted_entries = deleted_entries+leafs_deleter.deletedEntries deleted_entries = deleted_entries+leafs_deleter.deletedEntries

View File

@ -3,30 +3,30 @@ Do a search with the LDAP URL specified at command-line.
No output of LDAP data is produced except trace output. No output of LDAP data is produced except trace output.
""" """
from __future__ import print_function
import sys,getpass,ldap,ldapurl import sys,getpass,ldap,ldapurl
try: try:
ldapUrl = ldapurl.LDAPUrl(ldapUrl=sys.argv[1]) ldapUrl = ldapurl.LDAPUrl(ldapUrl=sys.argv[1])
except IndexError: except IndexError:
print 'Usage: %s [LDAP URL]' % (sys.argv[0]) print('Usage: %s [LDAP URL]' % (sys.argv[0]))
sys.exit(1) sys.exit(1)
for a in [ for a in [
'urlscheme','hostport','dn','attrs','scope', 'urlscheme','hostport','dn','attrs','scope',
'filterstr','extensions','who','cred' 'filterstr','extensions','who','cred'
]: ]:
print a,repr(getattr(ldapUrl,a)) print(a,repr(getattr(ldapUrl,a)))
l = ldap.initialize(ldapUrl.initializeUrl(),trace_level=1) l = ldap.initialize(ldapUrl.initializeUrl(),trace_level=1)
if ldapUrl.who!=None: if ldapUrl.who!=None:
if ldapUrl.cred!=None: if ldapUrl.cred!=None:
cred=ldapUrl.cred cred=ldapUrl.cred
else: else:
print 'Enter password for simple bind with',repr(ldapUrl.who) print('Enter password for simple bind with',repr(ldapUrl.who))
cred=getpass.getpass() cred=getpass.getpass()
l.simple_bind_s(ldapUrl.who,cred) l.simple_bind_s(ldapUrl.who,cred)
res = l.search_s(ldapUrl.dn,ldapUrl.scope,ldapUrl.filterstr,ldapUrl.attrs) res = l.search_s(ldapUrl.dn,ldapUrl.scope,ldapUrl.filterstr,ldapUrl.attrs)
print len(res),'search results' print(len(res),'search results')

View File

@ -7,6 +7,7 @@ ldap://localhost:1390 (LDAP with StartTLS)
ldaps://localhost:1391 (LDAP over SSL) ldaps://localhost:1391 (LDAP over SSL)
ldapi://%2ftmp%2fopenldap2 (domain socket /tmp/openldap2) ldapi://%2ftmp%2fopenldap2 (domain socket /tmp/openldap2)
""" """
from __future__ import print_function
import sys,os,ldap import sys,os,ldap
@ -23,10 +24,10 @@ ldap._trace_level = ldapmodule_trace_level
# Complete path name of the file containing all trusted CA certs # Complete path name of the file containing all trusted CA certs
CACERTFILE='/etc/ssl/ca-bundle.pem' CACERTFILE='/etc/ssl/ca-bundle.pem'
print """################################################################## print("""##################################################################
# LDAPv3 connection with StartTLS ext. op. # LDAPv3 connection with StartTLS ext. op.
################################################################## ##################################################################
""" """)
# Create LDAPObject instance # Create LDAPObject instance
l = ldap.initialize('ldap://localhost:1390',trace_level=ldapmodule_trace_level,trace_file=ldapmodule_trace_file) l = ldap.initialize('ldap://localhost:1390',trace_level=ldapmodule_trace_level,trace_file=ldapmodule_trace_file)
@ -44,8 +45,8 @@ l.set_option(ldap.OPT_X_TLS_NEWCTX,0)
# Now try StartTLS extended operation # Now try StartTLS extended operation
l.start_tls_s() l.start_tls_s()
print '***ldap.OPT_X_TLS_VERSION',l.get_option(ldap.OPT_X_TLS_VERSION) print('***ldap.OPT_X_TLS_VERSION',l.get_option(ldap.OPT_X_TLS_VERSION))
print '***ldap.OPT_X_TLS_CIPHER',l.get_option(ldap.OPT_X_TLS_CIPHER) print('***ldap.OPT_X_TLS_CIPHER',l.get_option(ldap.OPT_X_TLS_CIPHER))
# Try an explicit anon bind to provoke failure # Try an explicit anon bind to provoke failure
l.simple_bind_s('','') l.simple_bind_s('','')
@ -53,10 +54,10 @@ l.simple_bind_s('','')
# Close connection # Close connection
l.unbind_s() l.unbind_s()
print """################################################################## print("""##################################################################
# LDAPv3 connection over SSL # LDAPv3 connection over SSL
################################################################## ##################################################################
""" """)
# Create LDAPObject instance # Create LDAPObject instance
l = ldap.initialize('ldaps://localhost:1391',trace_level=ldapmodule_trace_level,trace_file=ldapmodule_trace_file) l = ldap.initialize('ldaps://localhost:1391',trace_level=ldapmodule_trace_level,trace_file=ldapmodule_trace_file)
@ -74,16 +75,16 @@ l.set_option(ldap.OPT_X_TLS_NEWCTX,0)
# Try an explicit anon bind to provoke failure # Try an explicit anon bind to provoke failure
l.simple_bind_s('','') l.simple_bind_s('','')
print '***ldap.OPT_X_TLS_VERSION',l.get_option(ldap.OPT_X_TLS_VERSION) print('***ldap.OPT_X_TLS_VERSION',l.get_option(ldap.OPT_X_TLS_VERSION))
print '***ldap.OPT_X_TLS_CIPHER',l.get_option(ldap.OPT_X_TLS_CIPHER) print('***ldap.OPT_X_TLS_CIPHER',l.get_option(ldap.OPT_X_TLS_CIPHER))
# Close connection # Close connection
l.unbind_s() l.unbind_s()
print """################################################################## print("""##################################################################
# LDAPv3 connection over Unix domain socket # LDAPv3 connection over Unix domain socket
################################################################## ##################################################################
""" """)
# Create LDAPObject instance # Create LDAPObject instance
l = ldap.initialize('ldapi://%2ftmp%2fopenldap-socket',trace_level=ldapmodule_trace_level,trace_file=ldapmodule_trace_file) l = ldap.initialize('ldapi://%2ftmp%2fopenldap-socket',trace_level=ldapmodule_trace_level,trace_file=ldapmodule_trace_file)

View File

@ -1,15 +1,16 @@
from __future__ import print_function
import ldap,ldapurl,pprint import ldap,ldapurl,pprint
from ldap.controls import LDAPControl,BooleanControl from ldap.controls import LDAPControl,BooleanControl
l = ldap.initialize('ldap://localhost:1390',trace_level=2) l = ldap.initialize('ldap://localhost:1390',trace_level=2)
print 60*'#' print(60*'#')
pprint.pprint(l.get_option(ldap.OPT_SERVER_CONTROLS)) pprint.pprint(l.get_option(ldap.OPT_SERVER_CONTROLS))
l.manage_dsa_it(1,1) l.manage_dsa_it(1,1)
pprint.pprint(l.get_option(ldap.OPT_SERVER_CONTROLS)) pprint.pprint(l.get_option(ldap.OPT_SERVER_CONTROLS))
print 60*'#' print(60*'#')
# Search with ManageDsaIT control (which has no value) # Search with ManageDsaIT control (which has no value)
pprint.pprint(l.search_ext_s( pprint.pprint(l.search_ext_s(
@ -19,7 +20,7 @@ pprint.pprint(l.search_ext_s(
['*','+'], ['*','+'],
serverctrls = [ LDAPControl('2.16.840.1.113730.3.4.2',1,None) ], serverctrls = [ LDAPControl('2.16.840.1.113730.3.4.2',1,None) ],
)) ))
print 60*'#' print(60*'#')
# Search with Subentries control (which has boolean value) # Search with Subentries control (which has boolean value)
pprint.pprint(l.search_ext_s( pprint.pprint(l.search_ext_s(
@ -30,4 +31,4 @@ pprint.pprint(l.search_ext_s(
serverctrls = [ BooleanControl('1.3.6.1.4.1.4203.1.10.1',1,1) ], serverctrls = [ BooleanControl('1.3.6.1.4.1.4203.1.10.1',1,1) ],
)) ))
print 60*'#' print(60*'#')

View File

@ -27,16 +27,17 @@
# Matched values control: (mail=*@example.org) # Matched values control: (mail=*@example.org)
# dn: uid=jsmith,ou=People,dc=example,dc=com # dn: uid=jsmith,ou=People,dc=example,dc=com
# mail: jsmith@example.org # mail: jsmith@example.org
from __future__ import print_function
import ldap import ldap
from ldap.controls import MatchedValuesControl from ldap.controls import MatchedValuesControl
def print_result(search_result): def print_result(search_result):
for n in range(len(search_result)): for n in range(len(search_result)):
print "dn: %s" % search_result[n][0] print("dn: %s" % search_result[n][0])
for attr in search_result[n][1].keys(): for attr in search_result[n][1].keys():
for i in range(len(search_result[n][1][attr])): for i in range(len(search_result[n][1][attr])):
print "%s: %s" % (attr, search_result[n][1][attr][i]) print("%s: %s" % (attr, search_result[n][1][attr][i]))
print print
@ -51,13 +52,13 @@ ld = ldap.initialize(uri)
mv = MatchedValuesControl(criticality=True, controlValue=control_filter) mv = MatchedValuesControl(criticality=True, controlValue=control_filter)
res = ld.search_ext_s(base, scope, filter, attrlist = ['mail']) res = ld.search_ext_s(base, scope, filter, attrlist = ['mail'])
print "LDAP filter used: %s" % filter print("LDAP filter used: %s" % filter)
print "Requesting 'mail' attribute back" print("Requesting 'mail' attribute back")
print print
print "No matched values control:" print("No matched values control:")
print_result(res) print_result(res)
res = ld.search_ext_s(base, scope, filter, attrlist = ['mail'], serverctrls = [mv]) res = ld.search_ext_s(base, scope, filter, attrlist = ['mail'], serverctrls = [mv])
print "Matched values control: %s" % control_filter print("Matched values control: %s" % control_filter)
print_result(res) print_result(res)

View File

@ -1,27 +1,28 @@
from __future__ import print_function
import ldap import ldap
host="localhost:1390" host="localhost:1390"
print "API info:",ldap.get_option(ldap.OPT_API_INFO) print("API info:",ldap.get_option(ldap.OPT_API_INFO))
print "debug level:",ldap.get_option(ldap.OPT_DEBUG_LEVEL) print("debug level:",ldap.get_option(ldap.OPT_DEBUG_LEVEL))
#print "Setting debug level to 255..." #print("Setting debug level to 255...")
#ldap.set_option(ldap.OPT_DEBUG_LEVEL,255) #ldap.set_option(ldap.OPT_DEBUG_LEVEL,255)
#print "debug level:",ldap.get_option(ldap.OPT_DEBUG_LEVEL) #print("debug level:",ldap.get_option(ldap.OPT_DEBUG_LEVEL))
print "default size limit:",ldap.get_option(ldap.OPT_SIZELIMIT) print("default size limit:",ldap.get_option(ldap.OPT_SIZELIMIT))
print "Setting default size limit to 10..." print("Setting default size limit to 10...")
ldap.set_option(ldap.OPT_SIZELIMIT,10) ldap.set_option(ldap.OPT_SIZELIMIT,10)
print "default size limit:",ldap.get_option(ldap.OPT_SIZELIMIT) print("default size limit:",ldap.get_option(ldap.OPT_SIZELIMIT))
print "Creating connection to",host,"..." print("Creating connection to",host,"...")
l=ldap.init(host) l=ldap.init(host)
print "size limit:",l.get_option(ldap.OPT_SIZELIMIT) print("size limit:",l.get_option(ldap.OPT_SIZELIMIT))
print "Setting connection size limit to 20..." print("Setting connection size limit to 20...")
l.set_option(ldap.OPT_SIZELIMIT,20) l.set_option(ldap.OPT_SIZELIMIT,20)
print "size limit:",l.get_option(ldap.OPT_SIZELIMIT) print("size limit:",l.get_option(ldap.OPT_SIZELIMIT))
#print "Setting time limit to 60 secs..." #print("Setting time limit to 60 secs...")
l.set_option(ldap.OPT_TIMELIMIT,60) l.set_option(ldap.OPT_TIMELIMIT,60)
#print "time limit:",l.get_option(ldap.OPT_TIMELIMIT) #print("time limit:",l.get_option(ldap.OPT_TIMELIMIT))
print "Binding..." print("Binding...")
l.simple_bind_s("","") l.simple_bind_s("","")

View File

@ -1,4 +1,5 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import print_function
url = "ldap://localhost:1390" url = "ldap://localhost:1390"
base = "dc=stroeder,dc=de" base = "dc=stroeder,dc=de"
@ -41,20 +42,20 @@ msgid = l.search_ext(
pages = 0 pages = 0
while True: while True:
pages += 1 pages += 1
print '-'*60 print('-'*60)
print "Getting page %d" % (pages) print("Getting page %d" % (pages))
rtype, rdata, rmsgid, serverctrls = l.result3(msgid,resp_ctrl_classes=known_ldap_resp_ctrls) rtype, rdata, rmsgid, serverctrls = l.result3(msgid,resp_ctrl_classes=known_ldap_resp_ctrls)
print '%d results' % len(rdata) print('%d results' % len(rdata))
print 'serverctrls=',pprint.pprint(serverctrls) print('serverctrls=',pprint.pprint(serverctrls))
print 'rdata=',pprint.pprint(rdata) print('rdata=',pprint.pprint(rdata))
pctrls = [ pctrls = [
c c
for c in serverctrls for c in serverctrls
if c.controlType == SimplePagedResultsControl.controlType if c.controlType == SimplePagedResultsControl.controlType
] ]
if pctrls: if pctrls:
print 'pctrls[0].size',repr(pctrls[0].size) print('pctrls[0].size',repr(pctrls[0].size))
print 'pctrls[0].cookie',repr(pctrls[0].cookie) print('pctrls[0].cookie',repr(pctrls[0].cookie))
if pctrls[0].cookie: if pctrls[0].cookie:
# Copy cookie from response control to request control # Copy cookie from response control to request control
req_ctrl.cookie = pctrls[0].cookie req_ctrl.cookie = pctrls[0].cookie
@ -68,7 +69,7 @@ while True:
else: else:
break break
else: else:
print "Warning: Server ignores RFC 2696 control." print("Warning: Server ignores RFC 2696 control.")
break break
l.unbind_s() l.unbind_s()

View File

@ -1,3 +1,4 @@
from __future__ import print_function
url = "ldap://localhost:1390/" url = "ldap://localhost:1390/"
base = "dc=stroeder,dc=de" base = "dc=stroeder,dc=de"
search_flt = r'(objectClass=*)' search_flt = r'(objectClass=*)'
@ -104,4 +105,4 @@ result_pages,all_results = l.paged_search_ext_s(
l.unbind_s() l.unbind_s()
print 'Received %d results in %d pages.' % (len(all_results),result_pages) print('Received %d results in %d pages.' % (len(all_results),result_pages))

View File

@ -1,6 +1,7 @@
""" """
Example showing the use of the password extended operation. Example showing the use of the password extended operation.
""" """
from __future__ import print_function
import sys,ldap,ldapurl,getpass import sys,ldap,ldapurl,getpass
@ -11,9 +12,9 @@ ldapmodule_trace_file = sys.stderr
lu = ldapurl.LDAPUrl(sys.argv[1]) lu = ldapurl.LDAPUrl(sys.argv[1])
print 'Old password' print('Old password')
oldpw = getpass.getpass() oldpw = getpass.getpass()
print 'New password' print('New password')
newpw = getpass.getpass() newpw = getpass.getpass()
# Set path name of file containing all CA certificates # Set path name of file containing all CA certificates

View File

@ -8,6 +8,7 @@ pyasn1
pyasn1-modules pyasn1-modules
python-ldap 2.4+ python-ldap 2.4+
""" """
from __future__ import print_function
from ldap.extop.dds import RefreshRequest,RefreshResponse from ldap.extop.dds import RefreshRequest,RefreshResponse
@ -17,7 +18,7 @@ try:
ldap_url = ldapurl.LDAPUrl(sys.argv[1]) ldap_url = ldapurl.LDAPUrl(sys.argv[1])
request_ttl = int(sys.argv[2]) request_ttl = int(sys.argv[2])
except (IndexError, ValueError): except (IndexError, ValueError):
print 'Usage: dds.py <LDAP URL> <TTL>' print('Usage: dds.py <LDAP URL> <TTL>')
sys.exit(1) sys.exit(1)
# Set debugging level # Set debugging level
@ -32,14 +33,14 @@ ldap_conn = ldap.ldapobject.LDAPObject(
) )
if ldap_url.cred is None: if ldap_url.cred is None:
print 'Password for %s:' % (repr(ldap_url.who)) print('Password for %s:' % (repr(ldap_url.who)))
ldap_url.cred = getpass.getpass() ldap_url.cred = getpass.getpass()
try: try:
ldap_conn.simple_bind_s(ldap_url.who or '',ldap_url.cred or '') ldap_conn.simple_bind_s(ldap_url.who or '',ldap_url.cred or '')
except ldap.INVALID_CREDENTIALS as e: except ldap.INVALID_CREDENTIALS as e:
print 'Simple bind failed:',str(e) print('Simple bind failed:',str(e))
sys.exit(1) sys.exit(1)
else: else:
@ -47,9 +48,9 @@ else:
try: try:
extop_resp_obj = ldap_conn.extop_s(extreq,extop_resp_class=RefreshResponse) extop_resp_obj = ldap_conn.extop_s(extreq,extop_resp_class=RefreshResponse)
except ldap.LDAPError as e: except ldap.LDAPError as e:
print str(e) print(str(e))
else: else:
if extop_resp_obj.responseTtl!=request_ttl: if extop_resp_obj.responseTtl!=request_ttl:
print 'Different response TTL:',extop_resp_obj.responseTtl print('Different response TTL:',extop_resp_obj.responseTtl)
else: else:
print 'Response TTL:',extop_resp_obj.responseTtl print('Response TTL:',extop_resp_obj.responseTtl)

View File

@ -9,6 +9,7 @@ pyasn1
pyasn1-modules pyasn1-modules
python-ldap 2.4+ python-ldap 2.4+
""" """
from __future__ import print_function
import sys,ldap,ldapurl,getpass import sys,ldap,ldapurl,getpass
@ -21,7 +22,7 @@ SEARCH_TIMEOUT=30.0
try: try:
ldap_url = ldapurl.LDAPUrl(sys.argv[1]) ldap_url = ldapurl.LDAPUrl(sys.argv[1])
except IndexError: except IndexError:
print 'Usage: noopsearch.py <LDAP URL>' print('Usage: noopsearch.py <LDAP URL>')
sys.exit(1) sys.exit(1)
# Set debugging level # Set debugging level
@ -36,14 +37,14 @@ ldap_conn = ldap.ldapobject.LDAPObject(
) )
if ldap_url.who and ldap_url.cred is None: if ldap_url.who and ldap_url.cred is None:
print 'Password for %s:' % (repr(ldap_url.who)) print('Password for %s:' % (repr(ldap_url.who)))
ldap_url.cred = getpass.getpass() ldap_url.cred = getpass.getpass()
try: try:
ldap_conn.simple_bind_s(ldap_url.who or '',ldap_url.cred or '') ldap_conn.simple_bind_s(ldap_url.who or '',ldap_url.cred or '')
except ldap.INVALID_CREDENTIALS as e: except ldap.INVALID_CREDENTIALS as e:
print 'Simple bind failed:',str(e) print('Simple bind failed:',str(e))
sys.exit(1) sys.exit(1)
try: try:
@ -67,5 +68,5 @@ noop_srch_ctrl = [
if c.controlType==SearchNoOpControl.controlType if c.controlType==SearchNoOpControl.controlType
][0] ][0]
print 'Number of search results: %d' % noop_srch_ctrl.numSearchResults print('Number of search results: %d' % noop_srch_ctrl.numSearchResults)
print 'Number of search continuations: %d' % noop_srch_ctrl.numSearchContinuations print('Number of search continuations: %d' % noop_srch_ctrl.numSearchContinuations)

View File

@ -9,6 +9,7 @@ pyasn1
pyasn1-modules pyasn1-modules
python-ldap 2.4+ python-ldap 2.4+
""" """
from __future__ import print_function
import sys,ldap,ldapurl,getpass import sys,ldap,ldapurl,getpass
@ -17,7 +18,7 @@ from ldap.controls.ppolicy import PasswordPolicyError,PasswordPolicyControl
try: try:
ldap_url = ldapurl.LDAPUrl(sys.argv[1]) ldap_url = ldapurl.LDAPUrl(sys.argv[1])
except (IndexError,ValueError): except (IndexError,ValueError):
print 'Usage: ppolicy.py <LDAP URL>' print('Usage: ppolicy.py <LDAP URL>')
sys.exit(1) sys.exit(1)
# Set debugging level # Set debugging level
@ -32,19 +33,19 @@ ldap_conn = ldap.ldapobject.LDAPObject(
) )
if ldap_url.cred is None: if ldap_url.cred is None:
print 'Password for %s:' % (repr(ldap_url.who)) print('Password for %s:' % (repr(ldap_url.who)))
ldap_url.cred = getpass.getpass() ldap_url.cred = getpass.getpass()
try: try:
msgid = ldap_conn.simple_bind(ldap_url.who,ldap_url.cred,serverctrls=[PasswordPolicyControl()]) msgid = ldap_conn.simple_bind(ldap_url.who,ldap_url.cred,serverctrls=[PasswordPolicyControl()])
res_type,res_data,res_msgid,res_ctrls = ldap_conn.result3(msgid) res_type,res_data,res_msgid,res_ctrls = ldap_conn.result3(msgid)
except ldap.INVALID_CREDENTIALS as e: except ldap.INVALID_CREDENTIALS as e:
print 'Simple bind failed:',str(e) print('Simple bind failed:',str(e))
sys.exit(1) sys.exit(1)
else: else:
if res_ctrls[0].controlType==PasswordPolicyControl.controlType: if res_ctrls[0].controlType==PasswordPolicyControl.controlType:
ppolicy_ctrl = res_ctrls[0] ppolicy_ctrl = res_ctrls[0]
print 'PasswordPolicyControl' print('PasswordPolicyControl')
print 'error',repr(ppolicy_ctrl.error),(ppolicy_ctrl.error!=None)*repr(PasswordPolicyError(ppolicy_ctrl.error)) print('error',repr(ppolicy_ctrl.error),(ppolicy_ctrl.error!=None)*repr(PasswordPolicyError(ppolicy_ctrl.error)))
print 'timeBeforeExpiration',repr(ppolicy_ctrl.timeBeforeExpiration) print('timeBeforeExpiration',repr(ppolicy_ctrl.timeBeforeExpiration))
print 'graceAuthNsRemaining',repr(ppolicy_ctrl.graceAuthNsRemaining) print('graceAuthNsRemaining',repr(ppolicy_ctrl.graceAuthNsRemaining))

View File

@ -10,6 +10,7 @@ pyasn1
pyasn1-modules pyasn1-modules
python-ldap 2.4+ python-ldap 2.4+
""" """
from __future__ import print_function
import sys,ldap,ldapurl,getpass import sys,ldap,ldapurl,getpass
@ -18,7 +19,7 @@ from ldap.controls.psearch import PersistentSearchControl,EntryChangeNotificatio
try: try:
ldap_url = ldapurl.LDAPUrl(sys.argv[1]) ldap_url = ldapurl.LDAPUrl(sys.argv[1])
except IndexError: except IndexError:
print 'Usage: psearch.py <LDAP URL>' print('Usage: psearch.py <LDAP URL>')
sys.exit(1) sys.exit(1)
# Set debugging level # Set debugging level
@ -33,14 +34,14 @@ ldap_conn = ldap.ldapobject.LDAPObject(
) )
if ldap_url.cred is None: if ldap_url.cred is None:
print 'Password for %s:' % (repr(ldap_url.who)) print('Password for %s:' % (repr(ldap_url.who)))
ldap_url.cred = getpass.getpass() ldap_url.cred = getpass.getpass()
try: try:
ldap_conn.simple_bind_s(ldap_url.who,ldap_url.cred) ldap_conn.simple_bind_s(ldap_url.who,ldap_url.cred)
except ldap.INVALID_CREDENTIALS as e: except ldap.INVALID_CREDENTIALS as e:
print 'Simple bind failed:',str(e) print('Simple bind failed:',str(e))
sys.exit(1) sys.exit(1)
psc = PersistentSearchControl() psc = PersistentSearchControl()
@ -64,7 +65,7 @@ while True:
resp_ctrl_classes={EntryChangeNotificationControl.controlType:EntryChangeNotificationControl}, resp_ctrl_classes={EntryChangeNotificationControl.controlType:EntryChangeNotificationControl},
) )
except ldap.TIMEOUT: except ldap.TIMEOUT:
print 'Timeout waiting for results...' print('Timeout waiting for results...')
else: else:
for dn,entry,srv_ctrls in res_data: for dn,entry,srv_ctrls in res_data:
ecn_ctrls = [ ecn_ctrls = [
@ -76,4 +77,4 @@ while True:
if ecn_ctrls: if ecn_ctrls:
changeType,previousDN,changeNumber = ecn_ctrls[0].changeType,ecn_ctrls[0].previousDN,ecn_ctrls[0].changeNumber changeType,previousDN,changeNumber = ecn_ctrls[0].changeType,ecn_ctrls[0].previousDN,ecn_ctrls[0].changeNumber
change_type_desc = CHANGE_TYPES_STR[changeType] change_type_desc = CHANGE_TYPES_STR[changeType]
print 'changeType: %s (%d), changeNumber: %s, previousDN: %s' % (change_type_desc,changeType,changeNumber,repr(previousDN)) print('changeType: %s (%d), changeNumber: %s, previousDN: %s' % (change_type_desc,changeType,changeNumber,repr(previousDN)))

View File

@ -6,6 +6,7 @@ Originally contributed by Andreas Hasenack <ahasenack@terra.com.br>
Requires module pyasn1 (see http://pyasn1.sourceforge.net/) Requires module pyasn1 (see http://pyasn1.sourceforge.net/)
""" """
from __future__ import print_function
import pprint,ldap,ldap.modlist import pprint,ldap,ldap.modlist
@ -16,10 +17,10 @@ uri = "ldap://localhost:2071/"
l = ldap.initialize(uri,trace_level=2) l = ldap.initialize(uri,trace_level=2)
l.simple_bind_s('uid=diradm,ou=schulung,dc=stroeder,dc=local','testsecret') l.simple_bind_s('uid=diradm,ou=schulung,dc=stroeder,dc=local','testsecret')
print """#--------------------------------------------------------------------------- print("""#---------------------------------------------------------------------------
# Add new entry # Add new entry
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
""" """)
new_test_dn = "uid=ablume,ou=Users,ou=schulung,dc=stroeder,dc=local" new_test_dn = "uid=ablume,ou=Users,ou=schulung,dc=stroeder,dc=local"
new_test_dn2 = "uid=ablume2,ou=Users,ou=schulung,dc=stroeder,dc=local" new_test_dn2 = "uid=ablume2,ou=Users,ou=schulung,dc=stroeder,dc=local"
@ -40,13 +41,13 @@ msg_id = l.add_ext(
serverctrls = [pr] serverctrls = [pr]
) )
_,_,_,resp_ctrls = l.result3(msg_id) _,_,_,resp_ctrls = l.result3(msg_id)
print "resp_ctrls[0].dn:",resp_ctrls[0].dn print("resp_ctrls[0].dn:",resp_ctrls[0].dn)
print "resp_ctrls[0].entry:";pprint.pprint(resp_ctrls[0].entry) print("resp_ctrls[0].entry:";pprint.pprint(resp_ctrls[0].entry))
print """#--------------------------------------------------------------------------- print("""#---------------------------------------------------------------------------
# Modify entry # Modify entry
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
""" """)
pr = PreReadControl(criticality=True,attrList=['uidNumber','gidNumber','entryCSN']) pr = PreReadControl(criticality=True,attrList=['uidNumber','gidNumber','entryCSN'])
@ -56,8 +57,8 @@ msg_id = l.modify_ext(
serverctrls = [pr] serverctrls = [pr]
) )
_,_,_,resp_ctrls = l.result3(msg_id) _,_,_,resp_ctrls = l.result3(msg_id)
print "resp_ctrls[0].dn:",resp_ctrls[0].dn print("resp_ctrls[0].dn:",resp_ctrls[0].dn)
print "resp_ctrls[0].entry:";pprint.pprint(resp_ctrls[0].entry) print("resp_ctrls[0].entry:";pprint.pprint(resp_ctrls[0].entry))
pr = PostReadControl(criticality=True,attrList=['uidNumber','gidNumber','entryCSN']) pr = PostReadControl(criticality=True,attrList=['uidNumber','gidNumber','entryCSN'])
@ -67,13 +68,13 @@ msg_id = l.modify_ext(
serverctrls = [pr] serverctrls = [pr]
) )
_,_,_,resp_ctrls = l.result3(msg_id) _,_,_,resp_ctrls = l.result3(msg_id)
print "resp_ctrls[0].dn:",resp_ctrls[0].dn print("resp_ctrls[0].dn:",resp_ctrls[0].dn)
print "resp_ctrls[0].entry:";pprint.pprint(resp_ctrls[0].entry) print("resp_ctrls[0].entry:";pprint.pprint(resp_ctrls[0].entry))
print """#--------------------------------------------------------------------------- print("""#---------------------------------------------------------------------------
# Rename entry # Rename entry
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
""" """)
pr = PostReadControl(criticality=True,attrList=['uid']) pr = PostReadControl(criticality=True,attrList=['uid'])
msg_id = l.rename( msg_id = l.rename(
@ -83,8 +84,8 @@ msg_id = l.rename(
serverctrls = [pr] serverctrls = [pr]
) )
_,_,_,resp_ctrls = l.result3(msg_id) _,_,_,resp_ctrls = l.result3(msg_id)
print "resp_ctrls[0].dn:",resp_ctrls[0].dn print("resp_ctrls[0].dn:",resp_ctrls[0].dn)
print "resp_ctrls[0].entry:";pprint.pprint(resp_ctrls[0].entry) print("resp_ctrls[0].entry:";pprint.pprint(resp_ctrls[0].entry))
pr = PreReadControl(criticality=True,attrList=['uid']) pr = PreReadControl(criticality=True,attrList=['uid'])
msg_id = l.rename( msg_id = l.rename(
@ -94,13 +95,13 @@ msg_id = l.rename(
serverctrls = [pr] serverctrls = [pr]
) )
_,_,_,resp_ctrls = l.result3(msg_id) _,_,_,resp_ctrls = l.result3(msg_id)
print "resp_ctrls[0].dn:",resp_ctrls[0].dn print("resp_ctrls[0].dn:",resp_ctrls[0].dn)
print "resp_ctrls[0].entry:";pprint.pprint(resp_ctrls[0].entry) print("resp_ctrls[0].entry:";pprint.pprint(resp_ctrls[0].entry))
print """#--------------------------------------------------------------------------- print("""#---------------------------------------------------------------------------
# Delete entry # Delete entry
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
""" """)
pr = PreReadControl(criticality=True,attrList=['*','+']) pr = PreReadControl(criticality=True,attrList=['*','+'])
msg_id = l.delete_ext( msg_id = l.delete_ext(
@ -108,5 +109,5 @@ msg_id = l.delete_ext(
serverctrls = [pr] serverctrls = [pr]
) )
_,_,_,resp_ctrls = l.result3(msg_id) _,_,_,resp_ctrls = l.result3(msg_id)
print "resp_ctrls[0].dn:",resp_ctrls[0].dn print("resp_ctrls[0].dn:",resp_ctrls[0].dn)
print "resp_ctrls[0].entry:";pprint.pprint(resp_ctrls[0].entry) print("resp_ctrls[0].entry:";pprint.pprint(resp_ctrls[0].entry))

View File

@ -8,6 +8,8 @@ Client-seitige Demo-Implementierung von Session Tracking Control
http://tools.ietf.org/html/draft-wahl-ldap-session-03 http://tools.ietf.org/html/draft-wahl-ldap-session-03
""" """
from __future__ import print_function
__version__ = '0.1' __version__ = '0.1'
import sys,getpass,ldap,ldapurl import sys,getpass,ldap,ldapurl
@ -17,7 +19,7 @@ from ldap.controls.sessiontrack import SessionTrackingControl,SESSION_TRACKING_F
try: try:
ldap_url = ldapurl.LDAPUrl(sys.argv[1]) ldap_url = ldapurl.LDAPUrl(sys.argv[1])
except (IndexError, ValueError): except (IndexError, ValueError):
print 'Usage: %s <LDAP URL>' % (sys.argv[0]) print('Usage: %s <LDAP URL>' % (sys.argv[0]))
sys.exit(1) sys.exit(1)
# Set debugging level # Set debugging level
@ -32,14 +34,14 @@ ldap_conn = ldap.ldapobject.LDAPObject(
) )
if ldap_url.who and ldap_url.cred is None: if ldap_url.who and ldap_url.cred is None:
print 'Password for %s:' % (repr(ldap_url.who)) print('Password for %s:' % (repr(ldap_url.who)))
ldap_url.cred = getpass.getpass() ldap_url.cred = getpass.getpass()
try: try:
ldap_conn.simple_bind_s(ldap_url.who or '',ldap_url.cred or '') ldap_conn.simple_bind_s(ldap_url.who or '',ldap_url.cred or '')
except ldap.INVALID_CREDENTIALS as e: except ldap.INVALID_CREDENTIALS as e:
print 'Simple bind failed:',str(e) print('Simple bind failed:',str(e))
sys.exit(1) sys.exit(1)
st_ctrl = SessionTrackingControl( st_ctrl = SessionTrackingControl(

View File

@ -14,6 +14,7 @@ pyasn1 0.1.4+
pyasn1-modules pyasn1-modules
python-ldap 2.4.10+ python-ldap 2.4.10+
""" """
from __future__ import print_function
# Import the python-ldap modules # Import the python-ldap modules
import ldap,ldapurl import ldap,ldapurl
@ -66,7 +67,7 @@ class SyncReplConsumer(ReconnectLDAPObject,SyncreplConsumer):
attributes['dn'] = dn attributes['dn'] = dn
self.__data[uuid] = attributes self.__data[uuid] = attributes
# Debugging # Debugging
print 'Detected', change_type, 'of entry:', dn print('Detected', change_type, 'of entry:', dn)
# If we have a cookie then this is not our first time being run, so it must be a change # If we have a cookie then this is not our first time being run, so it must be a change
if 'ldap_cookie' in self.__data: if 'ldap_cookie' in self.__data:
self.perform_application_sync(dn, attributes, previous_attributes) self.perform_application_sync(dn, attributes, previous_attributes)
@ -76,7 +77,7 @@ class SyncReplConsumer(ReconnectLDAPObject,SyncreplConsumer):
uuids = [uuid for uuid in uuids if uuid in self.__data] uuids = [uuid for uuid in uuids if uuid in self.__data]
# Delete all the UUID values we know of # Delete all the UUID values we know of
for uuid in uuids: for uuid in uuids:
print 'Detected deletion of entry:', self.__data[uuid]['dn'] print('Detected deletion of entry:', self.__data[uuid]['dn'])
del self.__data[uuid] del self.__data[uuid]
def syncrepl_present(self,uuids,refreshDeletes=False): def syncrepl_present(self,uuids,refreshDeletes=False):
@ -94,10 +95,10 @@ class SyncReplConsumer(ReconnectLDAPObject,SyncreplConsumer):
self.__presentUUIDs[uuid] = True self.__presentUUIDs[uuid] = True
def syncrepl_refreshdone(self): def syncrepl_refreshdone(self):
print 'Initial synchronization is now done, persist phase begins' print('Initial synchronization is now done, persist phase begins')
def perform_application_sync(self,dn,attributes,previous_attributes): def perform_application_sync(self,dn,attributes,previous_attributes):
print 'Performing application sync for:', dn print('Performing application sync for:', dn)
return True return True
@ -105,7 +106,7 @@ class SyncReplConsumer(ReconnectLDAPObject,SyncreplConsumer):
def commenceShutdown(signum, stack): def commenceShutdown(signum, stack):
# Declare the needed global variables # Declare the needed global variables
global watcher_running, ldap_connection global watcher_running, ldap_connection
print 'Shutting down!' print('Shutting down!')
# We are no longer running # We are no longer running
watcher_running = False watcher_running = False
@ -127,22 +128,22 @@ signal.signal(signal.SIGINT,commenceShutdown)
try: try:
ldap_url = ldapurl.LDAPUrl(sys.argv[1]) ldap_url = ldapurl.LDAPUrl(sys.argv[1])
database_path = sys.argv[2] database_path = sys.argv[2]
except IndexError,e: except IndexError as e:
print 'Usage:' print('Usage:')
print sys.argv[0], '<LDAP URL> <pathname of database>' print(sys.argv[0], '<LDAP URL> <pathname of database>')
print sys.argv[0], '\'ldap://127.0.0.1/cn=users,dc=test'\ print(sys.argv[0], '\'ldap://127.0.0.1/cn=users,dc=test'\)
'?*'\ '?*'\
'?sub'\ '?sub'\
'?(objectClass=*)'\ '?(objectClass=*)'\
'?bindname=uid=admin%2ccn=users%2cdc=test,'\ '?bindname=uid=admin%2ccn=users%2cdc=test,'\
'X-BINDPW=password\' db.shelve' 'X-BINDPW=password\' db.shelve'
sys.exit(1) sys.exit(1)
except ValueError,e: except ValueError as e:
print 'Error parsing command-line arguments:',str(e) print('Error parsing command-line arguments:',str(e))
sys.exit(1) sys.exit(1)
while watcher_running: while watcher_running:
print 'Connecting to LDAP server now...' print('Connecting to LDAP server now...')
# Prepare the LDAP server connection (triggers the connection as well) # Prepare the LDAP server connection (triggers the connection as well)
ldap_connection = SyncReplConsumer(database_path,ldap_url.initializeUrl()) ldap_connection = SyncReplConsumer(database_path,ldap_url.initializeUrl())
@ -150,15 +151,15 @@ while watcher_running:
try: try:
ldap_connection.simple_bind_s(ldap_url.who,ldap_url.cred) ldap_connection.simple_bind_s(ldap_url.who,ldap_url.cred)
except ldap.INVALID_CREDENTIALS as e: except ldap.INVALID_CREDENTIALS as e:
print 'Login to LDAP server failed: ', str(e) print('Login to LDAP server failed: ', str(e))
sys.exit(1) sys.exit(1)
except ldap.SERVER_DOWN: except ldap.SERVER_DOWN:
print 'LDAP server is down, going to retry.' print('LDAP server is down, going to retry.')
time.sleep(5) time.sleep(5)
continue continue
# Commence the syncing # Commence the syncing
print 'Commencing sync process' print('Commencing sync process')
ldap_search = ldap_connection.syncrepl_search( ldap_search = ldap_connection.syncrepl_search(
ldap_url.dn or '', ldap_url.dn or '',
ldap_url.scope or ldap.SCOPE_SUBTREE, ldap_url.scope or ldap.SCOPE_SUBTREE,
@ -177,6 +178,6 @@ while watcher_running:
except Exception as e: except Exception as e:
# Handle any exception # Handle any exception
if watcher_running: if watcher_running:
print 'Encountered a problem, going to retry. Error:', str(e) print('Encountered a problem, going to retry. Error:', str(e))
time.sleep(5) time.sleep(5)
pass pass

View File

@ -1,10 +1,11 @@
from __future__ import print_function
import ldap import ldap
from getpass import getpass from getpass import getpass
# Create LDAPObject instance # Create LDAPObject instance
l = ldap.initialize('ldap://localhost:1389',trace_level=1) l = ldap.initialize('ldap://localhost:1389',trace_level=1)
print 'Password:' print('Password:')
cred = getpass() cred = getpass()
try: try:
@ -15,7 +16,7 @@ try:
# Try a bind to provoke failure if protocol version is not supported # Try a bind to provoke failure if protocol version is not supported
l.bind_s('cn=root,dc=stroeder,dc=com',cred,ldap.AUTH_SIMPLE) l.bind_s('cn=root,dc=stroeder,dc=com',cred,ldap.AUTH_SIMPLE)
print 'Using rename_s():' print('Using rename_s():')
l.rename_s( l.rename_s(
'uid=fred,ou=Unstructured testing tree,dc=stroeder,dc=com', 'uid=fred,ou=Unstructured testing tree,dc=stroeder,dc=com',

View File

@ -9,6 +9,7 @@ See http://www.python-ldap.org for details.
Python compability note: Python compability note:
Requires Python 2.3+ Requires Python 2.3+
""" """
from __future__ import print_function
import ldap,ldap.resiter import ldap,ldap.resiter
@ -21,6 +22,6 @@ msgid = l.search('dc=stroeder,dc=de',ldap.SCOPE_SUBTREE,'(cn=m*)')
result_iter = l.allresults(msgid) result_iter = l.allresults(msgid)
for result_type,result_list,result_msgid,result_serverctrls in result_iter: for result_type,result_list,result_msgid,result_serverctrls in result_iter:
print result_type,result_list,result_msgid,result_serverctrls print(result_type,result_list,result_msgid,result_serverctrls)
l.unbind_s() l.unbind_s()

View File

@ -1,5 +1,6 @@
# For documentation, see comments in Module/LDAPObject.c and the # For documentation, see comments in Module/LDAPObject.c and the
# ldap.sasl module documentation. # ldap.sasl module documentation.
from __future__ import print_function
import ldap,ldap.sasl import ldap,ldap.sasl
@ -60,7 +61,7 @@ for ldap_uri,sasl_mech,sasl_cb_value_dict in [
), ),
]: ]:
sasl_auth = ldap.sasl.sasl(sasl_cb_value_dict,sasl_mech) sasl_auth = ldap.sasl.sasl(sasl_cb_value_dict,sasl_mech)
print 20*'*',sasl_auth.mech,20*'*' print(20*'*',sasl_auth.mech,20*'*')
# Open the LDAP connection # Open the LDAP connection
l = ldap.initialize(ldap_uri,trace_level=0) l = ldap.initialize(ldap_uri,trace_level=0)
# Set protocol version to LDAPv3 to enable SASL bind! # Set protocol version to LDAPv3 to enable SASL bind!
@ -68,15 +69,15 @@ for ldap_uri,sasl_mech,sasl_cb_value_dict in [
try: try:
l.sasl_interactive_bind_s("", sasl_auth) l.sasl_interactive_bind_s("", sasl_auth)
except ldap.LDAPError as e: except ldap.LDAPError as e:
print 'Error using SASL mechanism',sasl_auth.mech,str(e) print('Error using SASL mechanism',sasl_auth.mech,str(e))
else: else:
print 'Sucessfully bound using SASL mechanism:',sasl_auth.mech print('Sucessfully bound using SASL mechanism:',sasl_auth.mech)
try: try:
print 'Result of Who Am I? ext. op:',repr(l.whoami_s()) print('Result of Who Am I? ext. op:',repr(l.whoami_s()))
except ldap.LDAPError as e: except ldap.LDAPError as e:
print 'Error using SASL mechanism',sasl_auth.mech,str(e) print('Error using SASL mechanism',sasl_auth.mech,str(e))
try: try:
print 'OPT_X_SASL_USERNAME',repr(l.get_option(ldap.OPT_X_SASL_USERNAME)) print('OPT_X_SASL_USERNAME',repr(l.get_option(ldap.OPT_X_SASL_USERNAME)))
except AttributeError: except AttributeError:
pass pass

View File

@ -1,3 +1,4 @@
from __future__ import print_function
import sys,ldap,ldap.schema import sys,ldap,ldap.schema
schema_attrs = ldap.schema.SCHEMA_ATTRS schema_attrs = ldap.schema.SCHEMA_ATTRS
@ -9,39 +10,39 @@ ldap._trace_level = 0
subschemasubentry_dn,schema = ldap.schema.urlfetch(sys.argv[-1]) subschemasubentry_dn,schema = ldap.schema.urlfetch(sys.argv[-1])
if subschemasubentry_dn is None: if subschemasubentry_dn is None:
print 'No sub schema sub entry found!' print('No sub schema sub entry found!')
sys.exit(1) sys.exit(1)
if schema.non_unique_oids: if schema.non_unique_oids:
print '*** Schema errors ***' print('*** Schema errors ***')
print 'non-unique OIDs:\n','\r\n'.join(schema.non_unique_oids) print('non-unique OIDs:\n','\r\n'.join(schema.non_unique_oids))
print '*** Schema from',repr(subschemasubentry_dn) print('*** Schema from',repr(subschemasubentry_dn))
# Display schema # Display schema
for attr_type,schema_class in ldap.schema.SCHEMA_CLASS_MAPPING.items(): for attr_type,schema_class in ldap.schema.SCHEMA_CLASS_MAPPING.items():
print '*'*20,attr_type,'*'*20 print('*'*20,attr_type,'*'*20)
for element_id in schema.listall(schema_class): for element_id in schema.listall(schema_class):
se_orig = schema.get_obj(schema_class,element_id) se_orig = schema.get_obj(schema_class,element_id)
print attr_type,str(se_orig) print(attr_type,str(se_orig))
print '*** Testing object class inetOrgPerson ***' print('*** Testing object class inetOrgPerson ***')
drink = schema.get_obj(ldap.schema.AttributeType,'favouriteDrink') drink = schema.get_obj(ldap.schema.AttributeType,'favouriteDrink')
if not drink is None: if not drink is None:
print '*** drink ***' print('*** drink ***')
print 'drink.names',repr(drink.names) print('drink.names',repr(drink.names))
print 'drink.collective',repr(drink.collective) print('drink.collective',repr(drink.collective))
inetOrgPerson = schema.get_obj(ldap.schema.ObjectClass,'inetOrgPerson') inetOrgPerson = schema.get_obj(ldap.schema.ObjectClass,'inetOrgPerson')
if not inetOrgPerson is None: if not inetOrgPerson is None:
print inetOrgPerson.must,inetOrgPerson.may print(inetOrgPerson.must,inetOrgPerson.may)
print '*** person,organizationalPerson,inetOrgPerson ***' print('*** person,organizationalPerson,inetOrgPerson ***')
try: try:
print schema.attribute_types( print(schema.attribute_types()
['person','organizationalPerson','inetOrgPerson'] ['person','organizationalPerson','inetOrgPerson']
) )
print schema.attribute_types( print(schema.attribute_types()
['person','organizationalPerson','inetOrgPerson'], ['person','organizationalPerson','inetOrgPerson'],
attr_type_filter = [ attr_type_filter = [
('no_user_mod',[0]), ('no_user_mod',[0]),
@ -49,15 +50,15 @@ try:
] ]
) )
except KeyError as e: except KeyError as e:
print '***KeyError',str(e) print('***KeyError',str(e))
schema.ldap_entry() schema.ldap_entry()
print str(schema.get_obj(ldap.schema.MatchingRule,'2.5.13.0')) print(str(schema.get_obj(ldap.schema.MatchingRule,'2.5.13.0')))
print str(schema.get_obj(ldap.schema.MatchingRuleUse,'2.5.13.0')) print(str(schema.get_obj(ldap.schema.MatchingRuleUse,'2.5.13.0')))
print str(schema.get_obj(ldap.schema.AttributeType,'name')) print(str(schema.get_obj(ldap.schema.AttributeType,'name')))
print str(schema.get_inheritedobj(ldap.schema.AttributeType,'cn',['syntax','equality','substr','ordering'])) print(str(schema.get_inheritedobj(ldap.schema.AttributeType,'cn',['syntax','equality','substr','ordering'])))
must_attr,may_attr = schema.attribute_types(['person','organizationalPerson','inetOrgPerson'],raise_keyerror=0) must_attr,may_attr = schema.attribute_types(['person','organizationalPerson','inetOrgPerson'],raise_keyerror=0)

View File

@ -4,6 +4,7 @@ of a given server
Usage: schema_oc_tree.py [--html] [LDAP URL] Usage: schema_oc_tree.py [--html] [LDAP URL]
""" """
from __future__ import print_function
import sys,getopt,ldap,ldap.schema import sys,getopt,ldap,ldap.schema
@ -14,11 +15,11 @@ def PrintSchemaTree(schema,se_class,se_tree,se_oid,level):
"""ASCII text output for console""" """ASCII text output for console"""
se_obj = schema.get_obj(se_class,se_oid) se_obj = schema.get_obj(se_class,se_oid)
if se_obj!=None: if se_obj!=None:
print '| '*(level-1)+'+---'*(level>0), \ print('| '*(level-1)+'+---'*(level>0), \)
', '.join(se_obj.names), \ ', '.join(se_obj.names), \
'(%s)' % se_obj.oid '(%s)' % se_obj.oid
for sub_se_oid in se_tree[se_oid]: for sub_se_oid in se_tree[se_oid]:
print '| '*(level+1) print('| '*(level+1))
PrintSchemaTree(schema,se_class,se_tree,sub_se_oid,level+1) PrintSchemaTree(schema,se_class,se_tree,sub_se_oid,level+1)
@ -26,17 +27,17 @@ def HTMLSchemaTree(schema,se_class,se_tree,se_oid,level):
"""HTML output for browser""" """HTML output for browser"""
se_obj = schema.get_obj(se_class,se_oid) se_obj = schema.get_obj(se_class,se_oid)
if se_obj!=None: if se_obj!=None:
print """ print("""
<dt><strong>%s (%s)</strong></dt> <dt><strong>%s (%s)</strong></dt>
<dd> <dd>
%s %s
""" % (', '.join(se_obj.names),se_obj.oid,se_obj.desc) """ % (', '.join(se_obj.names),se_obj.oid,se_obj.desc))
if se_tree[se_oid]: if se_tree[se_oid]:
print '<dl>' print('<dl>')
for sub_se_oid in se_tree[se_oid]: for sub_se_oid in se_tree[se_oid]:
HTMLSchemaTree(schema,se_class,se_tree,sub_se_oid,level+1) HTMLSchemaTree(schema,se_class,se_tree,sub_se_oid,level+1)
print '</dl>' print('</dl>')
print '</dd>' print('</dd>')
ldap.set_option(ldap.OPT_DEBUG_LEVEL,0) ldap.set_option(ldap.OPT_DEBUG_LEVEL,0)
@ -46,13 +47,13 @@ ldap._trace_level = 0
subschemasubentry_dn,schema = ldap.schema.urlfetch(sys.argv[-1],ldap.trace_level) subschemasubentry_dn,schema = ldap.schema.urlfetch(sys.argv[-1],ldap.trace_level)
if subschemasubentry_dn is None: if subschemasubentry_dn is None:
print 'No sub schema sub entry found!' print('No sub schema sub entry found!')
sys.exit(1) sys.exit(1)
try: try:
options,args=getopt.getopt(sys.argv[1:],'',['html']) options,args=getopt.getopt(sys.argv[1:],'',['html'])
except getopt.error: except getopt.error:
print 'Error: %s\nUsage: schema_oc_tree.py [--html] [LDAP URL]' print('Error: %s\nUsage: schema_oc_tree.py [--html] [LDAP URL]')
html_output = options and options[0][0]=='--html' html_output = options and options[0][0]=='--html'
@ -60,41 +61,41 @@ oc_tree = schema.tree(ldap.schema.ObjectClass)
at_tree = schema.tree(ldap.schema.AttributeType) at_tree = schema.tree(ldap.schema.AttributeType)
#for k,v in oc_tree.items(): #for k,v in oc_tree.items():
# print k,'->',v # print(k,'->',v)
#for k,v in at_tree.items(): #for k,v in at_tree.items():
# print k,'->',v # print(k,'->',v)
if html_output: if html_output:
print """<html> print("""<html>
<head> <head>
<title>Object class tree</title> <title>Object class tree</title>
</head> </head>
<body bgcolor="#ffffff"> <body bgcolor="#ffffff">
<h1>Object class tree</h1> <h1>Object class tree</h1>
<dl> <dl>
""" """)
HTMLSchemaTree(schema,ldap.schema.ObjectClass,oc_tree,'2.5.6.0',0) HTMLSchemaTree(schema,ldap.schema.ObjectClass,oc_tree,'2.5.6.0',0)
print """</dl> print("""</dl>
<h1>Attribute type tree</h1> <h1>Attribute type tree</h1>
<dl> <dl>
""" """)
for a in schema.listall(ldap.schema.AttributeType): for a in schema.listall(ldap.schema.AttributeType):
if at_tree[a]: if at_tree[a]:
HTMLSchemaTree(schema,ldap.schema.AttributeType,at_tree,a,0) HTMLSchemaTree(schema,ldap.schema.AttributeType,at_tree,a,0)
print print
print """</dl> print("""</dl>
</body> </body>
</html> </html>
""" """)
else: else:
print '*** Object class tree ***\n' print('*** Object class tree ***\n')
print print
PrintSchemaTree(schema,ldap.schema.ObjectClass,oc_tree,'2.5.6.0',0) PrintSchemaTree(schema,ldap.schema.ObjectClass,oc_tree,'2.5.6.0',0)
print '\n*** Attribute types tree ***\n' print('\n*** Attribute types tree ***\n')
PrintSchemaTree(schema,ldap.schema.AttributeType,at_tree,'_',0) PrintSchemaTree(schema,ldap.schema.AttributeType,at_tree,'_',0)

View File

@ -1,3 +1,4 @@
from __future__ import print_function
import sys,getpass import sys,getpass
import ldap import ldap
@ -14,7 +15,7 @@ l.simple_bind_s(login_dn, login_pw)
try: try:
dn = "ou=CSEE,o=UQ,c=AU" dn = "ou=CSEE,o=UQ,c=AU"
print "Adding", repr(dn) print("Adding", repr(dn))
l.add_s(dn, l.add_s(dn,
[ [
("objectclass",["organizationalUnit"]), ("objectclass",["organizationalUnit"]),
@ -32,7 +33,7 @@ except _ldap.LDAPError:
# #
dn = "cn=David Leonard,ou=CSEE,o=UQ,c=AU" dn = "cn=David Leonard,ou=CSEE,o=UQ,c=AU"
print "Updating", repr(dn) print("Updating", repr(dn))
try: try:
l.delete_s(dn) l.delete_s(dn)
@ -100,7 +101,7 @@ res = l.search_s(
_ldap.SCOPE_SUBTREE, _ldap.SCOPE_SUBTREE,
"objectclass=*", "objectclass=*",
) )
print res print(res)
l.unbind() l.unbind()

View File

@ -3,6 +3,7 @@
# #
# simple LDAP server browsing example # simple LDAP server browsing example
# #
from __future__ import print_function
import ldap import ldap
import string import string
@ -11,7 +12,7 @@ from traceback import print_exc
url = "ldap://ldap.openldap.org/" url = "ldap://ldap.openldap.org/"
dn = "dc=openldap,dc=org" dn = "dc=openldap,dc=org"
print "Connecting to", url print("Connecting to", url)
l = ldap.initialize(url) l = ldap.initialize(url)
l.bind_s("", "", ldap.AUTH_SIMPLE); l.bind_s("", "", ldap.AUTH_SIMPLE);
@ -31,18 +32,18 @@ while 1:
try: try:
if cmd == "?": if cmd == "?":
print "cd <dn> - change DN to <dn>" print( "cd <dn> - change DN to <dn>")
print "cd <n> - change DN to number <n> of last 'ls'" print( "cd <n> - change DN to number <n> of last 'ls'")
print "cd - - change to previous DN" print( "cd - - change to previous DN")
print "cd .. - change to one-level higher DN" print( "cd .. - change to one-level higher DN")
print "cd - change to root DN" print( "cd - change to root DN")
print "ls - list children of crrent DN" print( "ls - list children of crrent DN")
print ". - show attributes of current DN" print( ". - show attributes of current DN")
print "/<expr> - list descendents matching filter <expr>" print( "/<expr> - list descendents matching filter <expr>")
print "? - show this help" print( "? - show this help")
elif cmd == "ls": elif cmd == "ls":
print "Children of", `dn`, ":" print("Children of", `dn`, ":")
dnlist = [] dnlist = []
# #
# List the children at one level down from the current dn # List the children at one level down from the current dn
@ -59,7 +60,7 @@ while 1:
shortname = name[:-len(dn)-2]+" +" shortname = name[:-len(dn)-2]+" +"
else: else:
shortname = name shortname = name
print " %3d. %s" % (len(dnlist), shortname) print(" %3d. %s" % (len(dnlist), shortname))
dnlist.append(name) dnlist.append(name)
elif cmd == "cd": elif cmd == "cd":
@ -80,7 +81,7 @@ while 1:
godn = arg godn = arg
else: else:
if dnlist is None: if dnlist is None:
print "do an ls first" print("do an ls first")
else: else:
godn = dnlist[i] godn = dnlist[i]
lastdn = dn lastdn = dn
@ -94,10 +95,10 @@ while 1:
# No attributes are listed, so the default is for # No attributes are listed, so the default is for
# the client to receive all attributes on the DN. # the client to receive all attributes on the DN.
# #
print "Attributes of", `dn`, ":" print("Attributes of", `dn`, ":")
for name,attrs in l.search_s(dn, ldap.SCOPE_BASE, for name,attrs in l.search_s(dn, ldap.SCOPE_BASE,
"objectclass=*"): "objectclass=*"):
print " %-24s" % name print(" %-24s" % name)
for k,vals in attrs.items(): for k,vals in attrs.items():
for v in vals: for v in vals:
if len(v) > 200: if len(v) > 200:
@ -105,7 +106,7 @@ while 1:
("... (%d bytes)" % len(v)) ("... (%d bytes)" % len(v))
else: else:
v = `v` v = `v`
print " %-12s: %s" % (k, v) print(" %-12s: %s" % (k, v))
elif cmd.startswith("/"): elif cmd.startswith("/"):
# #
@ -115,13 +116,13 @@ while 1:
# that we're not interested in them. # that we're not interested in them.
# #
expr = cmd[1:] expr = cmd[1:]
print "Descendents matching filter", `expr`, ":" print("Descendents matching filter", `expr`, ":")
for name,attrs in l.search_s(dn, ldap.SCOPE_SUBTREE, for name,attrs in l.search_s(dn, ldap.SCOPE_SUBTREE,
expr, []): expr, []):
print " %24s", name print(" %24s", name)
else: else:
print "unknown command - try '?' for help" print("unknown command - try '?' for help")
except: except:
print_exc() print_exc()

View File

@ -49,4 +49,4 @@ processing them in a for-loop.
for res_type,res_data,res_msgid,res_controls in l.allresults(msg_id): for res_type,res_data,res_msgid,res_controls in l.allresults(msg_id):
for dn,entry in res_data: for dn,entry in res_data:
# process dn and entry # process dn and entry
print dn,entry['objectClass'] print(dn,entry['objectClass'])

View File

@ -1120,6 +1120,6 @@ subtree search.
[('cn=Fred Feuerstein,ou=Testing,dc=stroeder,dc=de', {'cn': ['Fred Feuerstein']})] [('cn=Fred Feuerstein,ou=Testing,dc=stroeder,dc=de', {'cn': ['Fred Feuerstein']})]
>>> r = l.search_s('ou=Testing,dc=stroeder,dc=de',ldap.SCOPE_SUBTREE,'(objectClass=*)',['cn','mail']) >>> r = l.search_s('ou=Testing,dc=stroeder,dc=de',ldap.SCOPE_SUBTREE,'(objectClass=*)',['cn','mail'])
>>> for dn,entry in r: >>> for dn,entry in r:
>>> print 'Processing',repr(dn) >>> print('Processing',repr(dn))
>>> handle_ldap_entry(entry) >>> handle_ldap_entry(entry)

View File

@ -128,7 +128,7 @@ parse_ldap_url_tests = [
] ]
for ldap_url_str,test_ldap_url_obj in parse_ldap_url_tests: for ldap_url_str,test_ldap_url_obj in parse_ldap_url_tests:
# print '\nTesting LDAP URL:',repr(ldap_url) # print('\nTesting LDAP URL:',repr(ldap_url))
ldap_url_obj = LDAPUrl(ldapUrl=ldap_url_str) ldap_url_obj = LDAPUrl(ldapUrl=ldap_url_str)
print('#'*72) print('#'*72)
print(test_ldap_url_obj.unparse()) print(test_ldap_url_obj.unparse())