【发布时间】:2019-09-04 17:15:36
【问题描述】:
我正在尝试使用 python 代码运行基本的 ldap 查询并得到错误。 请帮我解决这个问题。 我已经尝试将代码从 Python 2 转换为 Python 3,因为有人说这是问题之一。
(project1_env) [root@localhost python-ldap]# cat script1.py
import ldap
## first you must open a connection to the server
try:
l = ldap.open("127.0.0.1")
## searching doesn't require a bind in LDAP V3. If you're using LDAP v2, set the next line appropriately
## and do a bind as shown in the above example.
# you can also set this to ldap.VERSION2 if you're using a v2 directory
# you should set the next option to ldap.VERSION2 if you're using a v2 directory
l.protocol_version = ldap.VERSION3
except ldap.LDAPError as e:
print (e)
# handle error however you like
## The next lines will also need to be changed to support your search requirements and directory
baseDN = "ou=Users, dc=afik, dc=com"
searchScope = ldap.SCOPE_SUBTREE
## retrieve all attributes - again adjust to your needs - see documentation for more options
retrieveAttributes = None
searchFilter = "cn=hr_user1"
try:
ldap_result_id = l.search(baseDN, searchScope, searchFilter, retrieveAttributes)
result_set = []
while 1:
result_type, result_data = l.result(ldap_result_id, 0)
if (result_data == []):
break
else:
## here you don't have to append to a list
## you could do whatever you want with the individual entry
## The appending to list is just for illustration.
if result_type == ldap.RES_SEARCH_ENTRY:
result_set.append(result_data)
print (result_set)
except ldap.LDAPError as e:
print (e)
(project1_env) [root@localhost python-ldap]# python script1.py
Traceback (most recent call last):
File "script1.py", line 9, in <module>
l = ldap.open("127.0.0.1")
AttributeError: module 'ldap' has no attribute 'open'
(project1_env) [root@localhost python-ldap]#
【问题讨论】:
-
当前目录下是否有名为
ldap.py的文件?你能告诉我们print(ldap.__file__)的输出吗? -
此文件不存在。