import ldap3
import sys

def discover_ldap(server_ip, port=3890):
    server_uri = f"ldap://{server_ip}:{port}"
    print(f"Connecting to {server_uri}...")
    
    server = ldap3.Server(server_uri, get_info=ldap3.ALL)
    conn = ldap3.Connection(server, auto_bind=False)
    
    try:
        if not conn.open():
            print("Could not open connection.")
            return

        print("\n--- Root DSE Information ---")
        if server.info:
            print(f"Naming Contexts: {server.info.naming_contexts}")
            print(f"Supported LDAP Versions: {server.info.supported_ldap_versions}")
            
            # For LLDAP, the namingContexts is usually dc=example,dc=com or similar
            if server.info.naming_contexts:
                base_dn = server.info.naming_contexts[0]
                print(f"Detected Base DN: {base_dn}")
                
                # Now try to explore structure (if allowed)
                print(f"\nSearching for users and groups in {base_dn} (Anonymous Search)...")
                
                # Search for user 'bede'
                conn.search(base_dn, '(uid=bede)', attributes=['*'])
                if conn.entries:
                    print(f"Found User 'bede': {conn.entries[0].entry_dn}")
                else:
                    print("Could not find user 'bede' via anonymous search.")
                
                # Search for group 'inventory'
                conn.search(base_dn, '(cn=inventory)', attributes=['*'])
                if conn.entries:
                    print(f"Found Group 'inventory': {conn.entries[0].entry_dn}")
                    print(f"Attributes: {conn.entries[0].entry_attributes}")
                else:
                    print("Could not find group 'inventory' via anonymous search.")
            else:
                print("No namingContexts found.")
        else:
            print("Could not retrieve Root DSE info.")
            
    except Exception as e:
        print(f"Error: {e}")
    finally:
        conn.unbind()

if __name__ == "__main__":
    discover_ldap("192.168.84.107")
