Last active
May 18, 2022 14:03
-
-
Save dansimau/3e6926f30ec4c63dab7f2ba83ab00c8d to your computer and use it in GitHub Desktop.
Recursively list users in an Azure AD group
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
#!/usr/bin/env python3 | |
import json | |
import subprocess | |
import sys | |
from typing import List | |
def list_users_in_groups(group_names: List[str]): | |
groups_stack: List[str] = group_names; | |
users: List[str] = []; | |
while len(groups_stack) > 0: | |
group_name = groups_stack.pop(0) | |
# print("Processing group %s" % group_name) | |
json_data = subprocess.check_output(["az", "ad", "group", "member", "list", "--group", group_name]) | |
data = json.loads(json_data) | |
for object in data: | |
if object["objectType"] == "Group": | |
# print("Adding group %s (%s) to stack..." % (object["mail"], object["objectId"])) | |
groups_stack.append(object["objectId"]) | |
elif object["objectType"] == "User": | |
if "mail" not in object: | |
raise Exception("user missing mail: %s" % object["objectid"]) | |
users.append(str.lower(object["mail"])) | |
else: | |
raise Exception("unknown object type: %s" % object["objectType"]) | |
return sorted(set(users)) | |
def main(args: List[str]): | |
print("\n".join(list_users_in_groups(args))) | |
def help(): | |
print("Usage: recursively-list-users-in-azure-ad-group.py <group name [..]>") | |
if __name__ == "__main__": | |
if len(sys.argv) < 2: | |
help() | |
else: | |
main(sys.argv[1:]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment