Python3使用ldap3获取LDAP服务器详情返回None问题求助
Hey there! Let's break down why your code is returning None for server.info and fix it up.
First, here's the code you shared:
from ldap3 import Server, Connection, ALL, NTLM
server = Server('servername', get_info=ALL)
conn = Connection(server, user="uname", password="pwd", authentication=NTLM)
print(server.info)
The Root Cause
The problem is that you've set up the Server and Connection objects, but you haven't actually bound (i.e., authenticated) the connection to the LDAP server. The ldap3 library doesn't fetch server metadata automatically when you create the Server instance—it only pulls that info after a successful bind.
Fixes to Try
Here are two straightforward ways to get your server info working:
1. Manually Call bind()
Explicitly bind the connection, then fetch the info. We'll also add error handling to catch bind failures:
from ldap3 import Server, Connection, ALL, NTLM # Initialize the server with request to fetch all info server = Server('servername', get_info=ALL) # Create the connection object conn = Connection(server, user="uname", password="pwd", authentication=NTLM) # Attempt to bind to the server if conn.bind(): # Now server.info will have the data you want! print(server.info) # Clean up by unbinding when done conn.unbind() else: # Print error details if bind fails print(f"Bind failed. Error details: {conn.result}")
2. Use auto_bind for Simpler Code
You can tell the Connection to bind automatically when it's created by adding the auto_bind parameter. This is a more concise approach:
from ldap3 import Server, Connection, ALL, NTLM server = Server('servername', get_info=ALL) # Auto-bind the connection on creation (use True or specify a binding mode) conn = Connection(server, user="uname", password="pwd", authentication=NTLM, auto_bind=True) # Server info is now available print(server.info) # The connection will auto-unbind when the script ends, or you can call conn.unbind() manually
Quick Tips for Troubleshooting
- Double-check your
servername—it should be the correct IP address or fully qualified domain name of your LDAP server. - For NTLM authentication, your username might need to be in
DOMAIN\usernameformat (e.g.,user="MYDOMAIN\uname"). - If binding fails, always check
conn.result—it contains detailed error messages that will help you pinpoint issues like wrong credentials or network problems.
内容的提问来源于stack exchange,提问作者Amruth

