Skip to content

Instantly share code, notes, and snippets.

@sharifsalah
Last active September 14, 2018 03:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sharifsalah/8399176 to your computer and use it in GitHub Desktop.
Save sharifsalah/8399176 to your computer and use it in GitHub Desktop.
Demo script to retrieve a list of Google Groups in a Google Apps domain based on the Directory API / Admin SDK. Requires access to an account with read access to groups and as well as a project with access to the the Admin SDK service.
#
# Copyright 2013 Sharif Salah
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# You'll need to download the client_secrets.json file for a valid project
# from the developer console with access to the Admin SDK APIs.
#!/usr/bin/env python
# standard imports for OAuth 2.0
import httplib2
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client.tools import run
from apiclient.discovery import build
# The location for the
CLIENT_SECRETS = 'client_secrets.json'
# a local file to store the oauth tokens
OAUTH2_STORAGE = 'oauth2.dat'
# the requested scopes for this script.
ADMIN_SCOPE = 'https://www.googleapis.com/auth/admin.directory.group'
API_VERSION = 'directory_v1'
ADMIN_URL = 'https://www.googleapis.com/admin/directory/%s/group' % (API_VERSION)
def main():
# Perform OAuth 2.0 authorization
flow = flow_from_clientsecrets(CLIENT_SECRETS, scope=ADMIN_SCOPE)
storage = Storage(OAUTH2_STORAGE)
credentials = storage.get()
# run the OAuth 2.0 flow if no credentials are available
# authorise once credentials are abtained
if credentials is None or credentials.invalid:
credentials = run(flow, storage)
http = httplib2.Http()
auth_http = credentials.authorize(http)
# Build the admin service
admin_service = build('admin', API_VERSION)
# Retrieve the list the groups in the domain
request = admin_service.groups().list(domain='your.domain.here')
response = request.execute(auth_http)
# Print out the list of groups
if response and 'groups' in response:
instances = response['groups']
for instance in instances:
print instance['name']
else:
print 'There are no users to list in this domain.'
if __name__ == '__main__':
main()
@dougmc
Copy link

dougmc commented Jun 14, 2016

Thanks for posting this. Very helpful.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment