Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ytensor42/58a9e9fe986c78a57bda14aad0782f7a to your computer and use it in GitHub Desktop.
Save ytensor42/58a9e9fe986c78a57bda14aad0782f7a to your computer and use it in GitHub Desktop.
List users with Google Directory API
#!/usr/bin/python
from apiclient.discovery import build
import httplib2
from oauth2client.service_account import ServiceAccountCredentials
from oauth2client.client import GoogleCredentials
import logging
import json
import sys
from apiclient import discovery
from apiclient import errors
import oauth2client
from oauth2client import client
from oauth2client import tools
from oauth2client.client import flow_from_clientsecrets
scope = 'https://www.googleapis.com/auth/admin.directory.user'
# A. with service accounts
#credentials = ServiceAccountCredentials.from_p12_keyfile('[email protected]',
# 'project1-5fc7d442817b.p12',
# scopes=scope)
#credentials = credentials.create_delegated('[email protected]')
# B. with client_secrets and login as domain admin
flow = flow_from_clientsecrets('client_secret.json',
scope=scope,
redirect_uri='urn:ietf:wg:oauth:2.0:oob')
auth_uri = flow.step1_get_authorize_url()
print 'goto the following url ' + auth_uri
code = raw_input('Enter token:')
credentials = flow.step2_exchange(code)
http = httplib2.Http()
http = credentials.authorize(http)
data = ''
service = discovery.build('admin', 'directory_v1', http=http)
page_token = None
while True:
try:
results = service.users().list(customer='C023zw3ee', domain='demoapp2.com', pageToken=page_token).execute()
users = results.get('users', [])
print json.dumps(users, sort_keys=True, indent=4)
for u in users:
print json.dumps(u['primaryEmail'], sort_keys=True, indent=4)
page_token = results.get('nextPageToken')
if not page_token:
break
except errors.HttpError, error:
print 'An error occurred: %s' % error
break
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment