Path: blob/master/add_to_team_drive.py
1635 views
from __future__ import print_function12import argparse3import glob4import googleapiclient.discovery5import json6import os7import pickle8import progress.bar9import sys10import time11from google.auth.transport.requests import Request12from google_auth_oauthlib.flow import InstalledAppFlow1314stt = time.time()1516parse = argparse.ArgumentParser(17description="A tool to add service accounts to a shared drive from a folder containing credential files."18)19parse.add_argument(20"--path",21"-p",22default="accounts",23help="Specify an alternative path to the service accounts folder.",24)25parse.add_argument(26"--credentials",27"-c",28default="./credentials.json",29help="Specify the relative path for the credentials file.",30)31parse.add_argument(32"--yes", "-y", default=False, action="store_true", help="Skips the sanity prompt."33)34parsereq = parse.add_argument_group("required arguments")35parsereq.add_argument(36"--drive-id", "-d", help="The ID of the Shared Drive.", required=True37)3839args = parse.parse_args()40acc_dir = args.path41did = args.drive_id42credentials = glob.glob(args.credentials)4344try:45open(credentials[0], "r")46print(">> Found credentials.")47except IndexError:48print(">> No credentials found.")49sys.exit(0)5051if not args.yes:52# input('Make sure the following client id is added to the shared drive as Manager:\n' + json.loads((open(53# credentials[0],'r').read()))['installed']['client_id'])54input(55">> Make sure the **Google account** that has generated credentials.json\n is added into your Team Drive "56"(shared drive) as Manager\n>> (Press any key to continue)"57)5859creds = None60if os.path.exists("token_sa.pickle"):61with open("token_sa.pickle", "rb") as token:62creds = pickle.load(token)63# If there are no (valid) credentials available, let the user log in.64if not creds or not creds.valid:65if creds and creds.expired and creds.refresh_token:66creds.refresh(Request())67else:68flow = InstalledAppFlow.from_client_secrets_file(69credentials[0],70scopes=[71"https://www.googleapis.com/auth/admin.directory.group",72"https://www.googleapis.com/auth/admin.directory.group.member",73],74)75# creds = flow.run_local_server(port=0)76creds = flow.run_console()77# Save the credentials for the next run78with open("token_sa.pickle", "wb") as token:79pickle.dump(creds, token)8081drive = googleapiclient.discovery.build("drive", "v3", credentials=creds)82batch = drive.new_batch_http_request()8384aa = glob.glob(f"{acc_dir}/*.json")85pbar = progress.bar.Bar("Readying accounts", max=len(aa))86for i in aa:87ce = json.loads(open(i, "r").read())["client_email"]88batch.add(89drive.permissions().create(90fileId=did,91supportsAllDrives=True,92body={"role": "organizer", "type": "user", "emailAddress": ce},93)94)95pbar.next()96pbar.finish()97print("Adding...")98batch.execute()99100print("Complete.")101hours, rem = divmod((time.time() - stt), 3600)102minutes, sec = divmod(rem, 60)103print("Elapsed Time:\n{:0>2}:{:0>2}:{:05.2f}".format(int(hours), int(minutes), sec))104105106