Posted on Leave a comment

Python Script Example with Main Method in Active Directory

Here is a simple Python script that interacts with Active Directory (AD) using the pyad library:

import pyad

def main():
    # Connect to the local Active Directory
    pyad.set_defaults(ldap_server="localhost")

    # Search for a user with the username "john.doe"
    user = pyad.aduser.ADUser.from_cn("john.doe")

    # Print the user's distinguished name (DN)
    print("User DN:", user.dn)

    # Print the user's email address
    print("Email:", user.get_attribute("mail"))

if __name__ == "__main__":
    main()

Note that in this example, the pyad library is assumed to be installed in your Python environment. If it is not, you can install it using the following command:

pip install pyad

Here is another example of a Python script that interacts with Active Directory (AD) using the ldap3 library:

from ldap3 import Server, Connection, ALL

def main():
    # Connect to the local Active Directory server
    server = Server("localhost", get_info=ALL)
    connection = Connection(server, auto_bind=True)

    # Search for a user with the username "john.doe"
    connection.search("dc=example,dc=com", "(cn=john.doe)", attributes=["dn", "mail"])

    # Get the search results
    results = connection.response

    # Print the user's distinguished name (DN) and email address
    if results:
        user = results[0]
        print("User DN:", user["dn"])
        print("Email:", user["attributes"]["mail"])
    else:
        print("User not found.")

if __name__ == "__main__":
    main()

Note that in this example, the ldap3 library is assumed to be installed in your Python environment. If it is not, you can install it using the following command:

pip install ldap3