在进行AD身份验证时,可能会出现Unable to obtain dns hostname of active directory domain controller with ntdsa object name的错误信息,这通常是由于无法获取活动目录域控制器的DNS主机名造成的。
要解决这个问题,可以使用以下代码示例,将其中的 “your_domain” 和 “your_domain_controller” 替换为你的域名和域控制器名称,然后再次尝试进行AD身份验证。
import socket
import os
from ldap3 import Server, Connection, ALL
from ldap3.core.exceptions import LDAPException
def domain_controller_dns_name():
dc_name = os.environ['LOGONSERVER'][2:]
dns_name = dc_name
try:
addr = socket.gethostbyname_ex(dc_name)
dns_name = addr[0]
except socket.gaierror:
pass
return dns_name
server_name = domain_controller_dns_name()
ldap_server = Server(server_name, get_info=ALL)
# Replace your_domain and your_domain_controller with your domain name and domain controller name.
bind_user = 'your_domain\\your_user'
bind_password = 'your_password'
with Connection(ldap_server, user=bind_user, password=bind_password) as conn:
try:
result = conn.search(search_base='dc=your_domain,dc=com',
search_filter='(objectClass=user)',
attributes=['cn', 'mail'])
print(result)
except LDAPException as e:
print('Exception:', e)
通过这个方式,可以获取到活动目录域控制器的DNS主机名,并正确进行AD身份验证。