Listing Google Workspace users, groups, and associated aliases with Python

This Python script makes use of Google’s service account credentials and impersonation to access the Admin SDK, listing users, groups, and associated aliases within the Workspace domain. Whether you’re managing a small business or a large enterprise, this script serves as a foundation for automating routine administrative tasks in a Workspace environment, enhancing efficiency and minimizing manual intervention.

Prerequisites

  1. Creating a service account
  2. Delegating domain-wide authority to the service account
  3. Downloading your service account credentials JSON file

Python Script

Before running the script, you might need to adjust the path to your JSON file containing service account credentials. Additionally, specifying the email address of your Workspace admin is essential to enable delegation and ensure proper access to your Workspace environment.

from google.oauth2 import service_account
from googleapiclient.discovery import build

# Scopes required for the Admin SDK
SCOPES = ['https://www.googleapis.com/auth/admin.directory.user',
          'https://www.googleapis.com/auth/admin.directory.group']

# Path to your service account key file
SERVICE_ACCOUNT_FILE = 'credentials.json'

# Create a service account credentials object
credentials = service_account.Credentials.from_service_account_file(
    SERVICE_ACCOUNT_FILE, scopes=SCOPES)

# Impersonation: Create delegated credentials
delegated_credentials = credentials.with_subject('admin@example.org')

# Build the Admin SDK service using delegated credentials
service = build('admin', 'directory_v1', credentials=delegated_credentials)

# Initialize counters
total_users = 0
total_groups = 0


def list_all_users():
    global total_users  # Declare global variable
    try:
        page_token = None

        while True:
            # Call the Admin SDK to list users with pageToken for pagination
            results = service.users().list(
                customer='my_customer',
                maxResults=500,  # Values must be within the range: [1 - 500]
                orderBy='email',
                pageToken=page_token
            ).execute()

            users = results.get('users', [])

            if not users:
                print('No more users found.')
                break
            else:
                print('Users:')
                for user in users:
                    print_user_info(user)

                total_users += len(users)  # Increment the total users count

            page_token = results.get('nextPageToken')

            if not page_token:
                print(f'>> All users retrieved. Total users: {total_users} <<\n')
                break  # No more pages, exit the loop

    except Exception as e:
        print(f'An error occurred: {e}')


def print_user_info(user):
    primary_email = user["primaryEmail"]
    full_name = user["name"]["fullName"]

    # Check if user has aliases
    aliases = user.get('aliases', [])

    # Print user information in one line
    print(f'{full_name} - {primary_email} {{{", ".join(aliases)}}}')


def list_all_groups():
    global total_groups  # Declare global variable
    try:
        page_token = None

        while True:
            # Call the Admin SDK to list groups with pageToken for pagination
            results = service.groups().list(
                customer='my_customer',
                maxResults=1000,  # Set a reasonably large value for maxResults
                pageToken=page_token
            ).execute()

            groups = results.get('groups', [])

            if not groups:
                print('No more groups found.')
                break
            else:
                print('Groups:')
                for group in groups:
                    print_group_info(group)

                total_groups += len(groups)  # Increment the total groups count

            page_token = results.get('nextPageToken')

            if not page_token:
                print(f'>> All groups retrieved. Total groups: {total_groups} <<\n')
                break  # No more pages, exit the loop

    except Exception as e:
        print(f'An error occurred: {e}')


def print_group_info(group):
    group_email = group["email"]

    # Check if group has aliases
    aliases = group.get('aliases', [])

    # Print group information in one line
    print(f'{group_email} {{{", ".join(aliases)}}}')


if __name__ == '__main__':
    list_all_users()
    list_all_groups()
asterix Written by:

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *