Created
March 22, 2023 15:02
-
-
Save TranKovak/a9693902119f938c137bac7aaba26105 to your computer and use it in GitHub Desktop.
The purpose is to search all computer in AD and list them in case you have a messy AD and need to find where is these XP computer that you can't find but have an alert in the security audit
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- encoding: utf-8 -*- | |
# | |
# Following script need loguru, pywin32 and pyad | |
# | |
# should work on python 3.10+ (tested on 3.11.2) | |
# | |
# The purpose is to search all computer in AD and list them in case you have a messy AD | |
# and need to find where is these XP computer that you can't find but have an alert in the security audit | |
# | |
import pyad.adquery | |
from loguru import logger | |
# Set up the logger | |
logger.add("computer_list.log", level="DEBUG") | |
# Set up the AD query object | |
q = pyad.adquery.ADQuery() | |
# Set the LDAP query filter to find all computers and their OS version | |
q.execute_query( | |
attributes=["cn", "operatingSystem", "operatingSystemVersion", "distinguishedName"], | |
where_clause="objectClass='computer'", | |
base_dn="DC=GRHSERVICES,DC=local" | |
) | |
# Sort the query results by operatingSystem | |
results = sorted(q.get_results(), key=lambda x: x["operatingSystem"]) | |
# Log the "Computers in the GRHSERVICES.local domain:" message at the SUCCESS level | |
logger.success("Computers in the GRHSERVICES.local domain:") | |
# Calculate the length of the longest computer name | |
max_name_length = max([len(row["cn"]) for row in results]) | |
# Log the computer information messages at the INFO level, with whitespace padding | |
for row in results: | |
# Retrieve the computer name, operating system, OS version, and OU location | |
computer_name = row["cn"] | |
operating_system = row["operatingSystem"] | |
os_version = row["operatingSystemVersion"] | |
ou = row.get("distinguishedName", "") | |
ou_parts = ou.split(",", maxsplit=1) | |
ou_location = ou_parts[1] if len(ou_parts) > 1 else "" | |
# Add whitespace padding to the computer name using f-strings | |
computer_name_padded = f"{computer_name:<{max_name_length + 2}}" | |
# Log the computer name, operating system, OS version, and OU location at the INFO level, with whitespace padding | |
logger.info(f"{computer_name_padded} ({operating_system} {os_version}) in {ou_location}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment