Skip to content

Instantly share code, notes, and snippets.

@smartass08
Last active May 19, 2020 15:54
Show Gist options
  • Save smartass08/1a50d03b1ac508c13346a082780a3b6d to your computer and use it in GitHub Desktop.
Save smartass08/1a50d03b1ac508c13346a082780a3b6d to your computer and use it in GitHub Desktop.
Script to add members to your gsuite group using admin directory api.
# Need credentials.json in root of the script
from __future__ import print_function
from google.oauth2.service_account import Credentials
import googleapiclient.discovery, json, progress.bar, glob, sys, argparse, time
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
import os
import pickle
parse = argparse.ArgumentParser(description='A tool to add any email to your gsuite group')
parsereq = parse.add_argument_group('required arguments')
parsereq.add_argument('--groupaddr', '-g', help='The address of groups for your organization.', required=True)
parsereq.add_argument('--emailaddr', '-e', help='The address of email to be added into the group.', required=True)
parse.add_argument('--credentials', '-c', default='credentials.json', help='Specify the relative path for the controller file.')
args = parse.parse_args()
group = args.groupaddr
mail = args.emailaddr
credentials = glob.glob(args.credentials)
creds = None
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(credentials[0], scopes=[
'https://www.googleapis.com/auth/admin.directory.group',
'https://www.googleapis.com/auth/admin.directory.group.member'
])
# creds = flow.run_local_server(port=0)
creds = flow.run_console()
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
def AddMembers(drive, email, groups):
body = {"email": email, "role": "MEMBER"}
drive.members().insert(groupKey=groups, body=body).execute()
def main():
service = googleapiclient.discovery.build("admin", "directory_v1", credentials=creds)
AddMembers(service, mail, group)
print("Email successfully added!")
if __name__ == "__main__":
main()
@smartass08
Copy link
Author

Inspired from :- Here

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