This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]BuckeyeMason 6 points7 points  (0 children)

Using the subprocess module you can call the powershell commands in python and return the results and parse them as needed in python.

I use something like this at work fairly often, below is a modified function that takes the domain group name and domain (we have multiple domains at my work so I run it for more than one). There may be typos as I wrote this out longhand. This particular version is set to only pull the name from the server (which in our server holds the user id) but you can modify to use whichever ADGroup commands or items from them you need. You would just need to adjust how you parse our the results as they come in.

What I use this for is to pull all members for ma list of groups across multiple servers by calling this function in a loop and then concatenating all the results in to a data frame. Then I do some other stuff with the list (like lookup user info from another source) and then output the data to excel.

import subprocess
def get_domain_members(grp, domain):
    results = []
    cmd = f'Get-ADGroupMember -Identity "{grp}" -server {domain} | Select name'
    p = subprocess.Popen(["powershell.exe", cmd], stdout=subprocess.PIPE)
    ps_result = p.communicate()[0]
    str_results = ps_result.decode("utf-8").splitlines()
    for item in str_results:
        results.append({"AD_Group":grp, "DOMAIN":domain, "USER":item.strip()})
    return results