Skip to content

Instantly share code, notes, and snippets.

@b4ldr
Created June 8, 2020 15:01
Show Gist options
  • Save b4ldr/1596149c0f9c0a2b7b4452173c060409 to your computer and use it in GitHub Desktop.
Save b4ldr/1596149c0f9c0a2b7b4452173c060409 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
"""A simple example of how to access the Google Analytics API."""
from argparse import ArgumentParser
from apiclient.discovery import build
from google.oauth2 import service_account
def get_args():
"""Parse arguments"""
parser = ArgumentParser(description=__doc__)
parser.add_argument('-i', '--impersonate', help='A super admin email address')
parser.add_argument('-D', '--domain', help='The DNS domain to search')
parser.add_argument('key_file_location',
help='The path to a valid service account JSON key file')
return parser.parse_args()
def get_service(api_name, api_version, scopes, key_file_location, impersonate):
"""Get a service that communicates to a Google API.
Args:
api_name: The name of the api to connect to.
api_version: The api version to connect to.
scopes: A list auth scopes to authorize for the application.
key_file_location: The path to a valid service account JSON key file.
impersonate: A super admin email address to impersonate
Returns:
A service that is connected to the specified API.
"""
credentials = service_account.Credentials.from_service_account_file(
key_file_location, scopes=scopes)
credentials = credentials.with_subject(impersonate)
# Build the service object.
service = build(api_name, api_version, credentials=credentials)
return service
def main():
"""Main entry point"""
# Define the auth scopes to request.
scopes = [
'https://www.googleapis.com/auth/admin.directory.user.readonly',
# 'https://www.googleapis.com/auth/admin.directory.group.readonly',
# 'https://www.googleapis.com/auth/admin.directory.group.member.readonly',
# 'https://www.googleapis.com/auth/admin.directory.orgunit.readonly',
# 'https://www.googleapis.com/auth/admin.directory.user.alias.readonly',
# 'https://www.googleapis.com/auth/admin.directory.userschema.readonly',
]
args = get_args()
key_file_location = args.key_file_location
# Authenticate and construct service.
service = get_service(
api_name='admin',
api_version='directory_v1',
scopes=scopes,
key_file_location=key_file_location,
impersonate=args.impersonate)
results = service.users().list(domain=args.domain).execute()
for user in results.get('users', []):
print(user['primaryEmail'])
if __name__ == '__main__':
main()
scripts/gs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment