Categories: PlaybooksScripts

Python Script to Query Active Directory

Here is a basic Python script to query Active Directory using the “ldap3” library. Useful script code for authentication.

import ldap3

server = ldap3.Server("ldap://hostname:port/")
conn = ldap3.Connection(server, "CN=username,DC=domain,DC=com", "password")
conn.bind()

query = "(&(objectCategory=person)(objectClass=user)(cn=*))"
conn.search("DC=domain,DC=com", query, attributes=["cn", "mail", "memberOf"])

result = conn.response

for item in result:
    print(item["attributes"])

conn.unbind()

Replace the placeholders with the appropriate values for your Active Directory:

  • “hostname” and “port” are the address and port of the Active Directory server
  • “username” is the username of an account with permission to search the directory
  • “password” is the password for the account
  • “domain” is the domain name of your Active Directory
  • “cn=*” can be modified to search for specific common names.

The “attributes” list in the conn.search() call can be modified to retrieve other properties of the users in the directory.

PyJoy

Recent Posts

Python Script to Monitor Network Traffic

Here is a simple Python script to monitor network traffic. import psutil def monitor_network(): #…

2 years ago

Python Script for Web Scraping

Here's a basic example of web scraping in Python using the requests and BeautifulSoup libraries:…

2 years ago

Python Script to SSH and Run Commands

Here's an example of how you can use Python to SSH into a remote server…

2 years ago

Python Code Example with Classes

Here's an example of a Python class that represents a rectangle: class Rectangle: def __init__(self,…

2 years ago

Python Script Example with Main Method in Active Directory

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

2 years ago

Python Script Example for System Administrators

Here's a Python script to monitor disk usage on a system and send an email…

2 years ago