Query Active Directory over LDAP in Python to extract user objects with Service Principal Names (SPNs) registered.
from ldap3 import Server, Connection, ALL, NTLM
def enumerate_spn_users(dc_ip: str, domain: str, user: str, password: str):
server = Server(dc_ip, get_info=ALL)
conn = Connection(server, user=f"{domain}\\{user}", password=password, authentication=NTLM)
if not conn.bind():
return []
search_filter = "(&(objectClass=user)(servicePrincipalName=*))"
conn.search(
search_base=f"DC={domain.replace('.', ',DC=')}",
search_filter=search_filter,
attributes=['sAMAccountName', 'servicePrincipalName']
)
return conn.entries